HttpWebRequest.jvm.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Specialized;
  4. using System.Configuration;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Runtime;
  8. using System.Runtime.CompilerServices;
  9. using System.Runtime.Serialization;
  10. using System.Security;
  11. using System.Security.Cryptography.X509Certificates;
  12. using System.Security.Permissions;
  13. using System.Text;
  14. using System.Threading;
  15. using System.Net;
  16. namespace System.Net
  17. {
  18. [Serializable]
  19. public class HttpWebRequest : WebRequest
  20. {
  21. #region Fields
  22. private static readonly int DEFAULT_MAX_RESP_HEADER_LEN = 64;
  23. private static int _defaultMaxResponseHeadersLength = DEFAULT_MAX_RESP_HEADER_LEN;
  24. private HttpProvider _provider;
  25. #endregion
  26. #region Constructors
  27. internal HttpWebRequest(Uri uri)
  28. {
  29. _provider = HttpProvider.GetHttpProvider(uri);
  30. // Console.WriteLine("uri to string: " + uri.ToString());
  31. }
  32. #endregion
  33. #region Properties
  34. public string Accept
  35. {
  36. get{return Headers["Accept"];}
  37. set
  38. {
  39. if(_provider.IsRequestStarted ())
  40. throw new InvalidOperationException ("request started");
  41. _provider.Headers.RemoveAndAdd ("Accept", value);
  42. }
  43. }
  44. public Uri Address
  45. {
  46. get{return _provider.GetAddress();}
  47. }
  48. public bool AllowAutoRedirect
  49. {
  50. get{return _provider.AllowAutoRedirect;}
  51. set{_provider.AllowAutoRedirect = value;}
  52. }
  53. public bool AllowWriteStreamBuffering
  54. {
  55. get{return _provider.AllowWriteStreamBuffering;}
  56. set{_provider.AllowWriteStreamBuffering = value;}
  57. }
  58. [MonoTODO] //documentation related
  59. public X509CertificateCollection ClientCertificates
  60. {
  61. [MonoTODO]
  62. get{return _provider.GetX509Certificates();}
  63. [MonoNotSupported("")]
  64. set { throw new NotImplementedException (); }
  65. }
  66. public string Connection
  67. {
  68. get { return Headers["Connection"]; }
  69. set
  70. {
  71. if(_provider.IsRequestStarted())
  72. throw new InvalidOperationException ("request started");
  73. string val = value;
  74. if (val != null)
  75. val = val.Trim ().ToLower (CultureInfo.InvariantCulture);
  76. if (val == null || val.Length == 0)
  77. {
  78. Headers.RemoveInternal ("Connection");
  79. return;
  80. }
  81. if (val == "keep-alive" || val == "close")
  82. throw new ArgumentException ("Keep-Alive and Close may not be set with this property");
  83. // if (this.KeepAlive && val.IndexOf ("keep-alive") == -1)
  84. // value = value + ", Keep-Alive";
  85. Headers.RemoveAndAdd ("Connection", value);
  86. }
  87. }
  88. public override string ConnectionGroupName
  89. {
  90. get{return _provider.ConnectionGroupName;}
  91. set{_provider.ConnectionGroupName = value;}
  92. }
  93. public override long ContentLength
  94. {
  95. get{return _provider.ContentLength;}
  96. set
  97. {
  98. if(_provider.IsRequestStarted())
  99. throw new InvalidOperationException("Connection already opened");
  100. _provider.ContentLength = value;
  101. }
  102. }
  103. public override string ContentType
  104. {
  105. get { return Headers["Content-Type"]; }
  106. set
  107. {
  108. if (value == null || value.Trim().Length == 0)
  109. {
  110. Headers.RemoveInternal ("Content-Type");
  111. return;
  112. }
  113. Headers.RemoveAndAdd ("Content-Type", value);
  114. }
  115. }
  116. [MonoTODO] //needed for automatic documentation tools,
  117. //since currently we don't support this feature
  118. public HttpContinueDelegate ContinueDelegate
  119. {
  120. [MonoTODO]
  121. get{return _provider.ContinueDelegate;}
  122. [MonoTODO]
  123. set{_provider.ContinueDelegate = value;}
  124. }
  125. public CookieContainer CookieContainer
  126. {
  127. get{return _provider.CookieContainer;}
  128. set{_provider.CookieContainer = value;}
  129. }
  130. public override ICredentials Credentials
  131. {
  132. get{return _provider.Credentials;}
  133. set{_provider.Credentials = value;}
  134. }
  135. public static int DefaultMaximumResponseHeadersLength
  136. {
  137. get{return HttpProvider.DefaultMaxResponseHeadersLength;}
  138. set{HttpProvider.DefaultMaxResponseHeadersLength = value;}
  139. }
  140. public string Expect
  141. {
  142. get{return Headers["Expect"];}
  143. set
  144. {
  145. if(_provider.IsRequestStarted ())
  146. throw new InvalidOperationException("Connection already opened");
  147. string val = value;
  148. if (val != null)
  149. val = val.Trim ().ToLower (CultureInfo.InvariantCulture);
  150. if (val == null || val.Length == 0)
  151. {
  152. Headers.RemoveInternal ("Expect");
  153. return;
  154. }
  155. if (val == "100-continue")
  156. throw new ArgumentException ("100-Continue cannot be set with this property.",
  157. "value");
  158. Headers.RemoveAndAdd ("Expect", value);
  159. }
  160. }
  161. public bool HaveResponse
  162. {
  163. get{return _provider.IsHaveResponse();}
  164. }
  165. public override WebHeaderCollection Headers
  166. {
  167. get{return _provider.Headers;}
  168. set{_provider.Headers = value;}
  169. }
  170. public DateTime IfModifiedSince
  171. {
  172. get
  173. {
  174. string str = Headers["If-Modified-Since"];
  175. if (str == null)
  176. return DateTime.Now;
  177. try
  178. {
  179. return MonoHttpDate.Parse (str);
  180. }
  181. catch (Exception)
  182. {
  183. return DateTime.Now;
  184. }
  185. }
  186. set
  187. {
  188. if(_provider.IsRequestStarted ())
  189. throw new InvalidOperationException("Connection already started");
  190. // rfc-1123 pattern
  191. Headers.SetInternal ("If-Modified-Since",
  192. value.ToUniversalTime ().ToString ("r", null));
  193. // TODO: check last param when using different locale
  194. }
  195. }
  196. public bool KeepAlive
  197. {
  198. get{return _provider.KeepAlive;}
  199. set{_provider.KeepAlive = value;}
  200. }
  201. public int MaximumAutomaticRedirections
  202. {
  203. get{return _provider.MaxAutoRedirections;}
  204. set{_provider.MaxAutoRedirections = value;}
  205. }
  206. [MonoTODO] //documentation
  207. public int MaximumResponseHeadersLength
  208. {
  209. [MonoTODO]
  210. get{return _provider.MaximumResponseHeadersLength;}
  211. [MonoTODO]
  212. set{_provider.MaximumResponseHeadersLength = value;}
  213. }
  214. public string MediaType
  215. {
  216. get{return _provider.MediaType;}
  217. set{_provider.MediaType = value;}
  218. }
  219. public override string Method
  220. {
  221. get{return _provider.MethodName;}
  222. set{_provider.MethodName = value;}
  223. }
  224. [MonoTODO] //for documentation related - limited.
  225. public bool Pipelined
  226. {
  227. [MonoTODO]
  228. get{return _provider.Pipelined;}
  229. [MonoTODO]
  230. set{_provider.Pipelined = value;}
  231. }
  232. public override bool PreAuthenticate
  233. {
  234. get{return _provider.PreAuthenticate;}
  235. set{_provider.PreAuthenticate = value;}
  236. }
  237. public Version ProtocolVersion
  238. {
  239. get{return _provider.ProtocolVersion;}
  240. set{_provider.ProtocolVersion = value;}
  241. }
  242. public override IWebProxy Proxy
  243. {
  244. get{return _provider.Proxy;}
  245. set{_provider.Proxy = value;}
  246. }
  247. public int ReadWriteTimeout
  248. {
  249. get{return _provider.ReadWriteTimeout;}
  250. set{_provider.ReadWriteTimeout = value;}
  251. }
  252. public string Referer
  253. {
  254. get {return Headers["Referer"];}
  255. set
  256. {
  257. if(_provider.IsRequestStarted ())
  258. throw new InvalidOperationException("Connection already opened");
  259. if (value == null || value.Trim().Length == 0)
  260. {
  261. Headers.RemoveInternal ("Referer");
  262. return;
  263. }
  264. Headers.SetInternal ("Referer", value);
  265. }
  266. }
  267. internal Uri AuthUri
  268. {
  269. get { return RequestUri; }
  270. }
  271. public override Uri RequestUri
  272. {
  273. get{return _provider.GetOriginalAddress();}
  274. }
  275. public bool SendChunked
  276. {
  277. get{return _provider.SendChunked;}
  278. set{_provider.SendChunked = value;}
  279. }
  280. public ServicePoint ServicePoint
  281. {
  282. get{return _provider.ServicePoint;}
  283. }
  284. [MonoTODO] //once again - needed since our impl. still
  285. //doesn't support this feature we need document it..
  286. public override int Timeout
  287. {
  288. [MonoTODO]
  289. get{return _provider.Timeout;}
  290. [MonoTODO]
  291. set{_provider.Timeout = value;}
  292. }
  293. public string TransferEncoding
  294. {
  295. get { return Headers ["Transfer-Encoding"]; }
  296. set
  297. {
  298. if(_provider.IsRequestStarted ())
  299. {
  300. throw new InvalidOperationException("Connection has been already opened");
  301. }
  302. string val = value;
  303. if (val != null)
  304. val = val.Trim ().ToLower (CultureInfo.InvariantCulture);
  305. if (val == null || val.Length == 0)
  306. {
  307. Headers.RemoveInternal ("Transfer-Encoding");
  308. return;
  309. }
  310. if (val == "chunked")
  311. throw new ArgumentException ("Chunked encoding must be set with the SendChunked property");
  312. if (!this.SendChunked)
  313. throw new InvalidOperationException ("SendChunked must be True");
  314. Headers.RemoveAndAdd ("Transfer-Encoding", value);
  315. }
  316. }
  317. public bool UnsafeAuthenticatedConnectionSharing
  318. {
  319. get { throw new NotImplementedException (); }
  320. set { throw new NotImplementedException (); }
  321. }
  322. public string UserAgent
  323. {
  324. get { return Headers ["User-Agent"]; }
  325. set { Headers.SetInternal ("User-Agent", value); }
  326. }
  327. #endregion
  328. #region Methods
  329. //todo
  330. public override void Abort()
  331. {
  332. _provider.Abort();
  333. // _connection.disconnect();
  334. // _haveResponse = true;
  335. // //aborted = true;
  336. // if (_asyncWrite != null)
  337. // {
  338. // GHWebAsyncResult r = _asyncWrite;
  339. // WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
  340. // r.SetCompleted (false, wexc);
  341. // r.DoCallback ();
  342. // _asyncWrite = null;
  343. // }
  344. //
  345. // if (_asyncRead != null)
  346. // {
  347. // GHWebAsyncResult r = _asyncRead;
  348. // WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
  349. // r.SetCompleted (false, wexc);
  350. // r.DoCallback ();
  351. // _asyncRead = null;
  352. // }
  353. //
  354. //// if (abortHandler != null)
  355. //// {
  356. //// try
  357. //// {
  358. //// abortHandler (this, EventArgs.Empty);
  359. //// }
  360. //// catch {}
  361. //// abortHandler = null;
  362. //// }
  363. //
  364. // if (_writeStream != null)
  365. // {
  366. // try
  367. // {
  368. // _writeStream.Close ();
  369. // _writeStream = null;
  370. // }
  371. // catch {}
  372. // }
  373. //
  374. // if (_response != null)
  375. // {
  376. // try
  377. // {
  378. // _response.Close ();
  379. // _response = null;
  380. // }
  381. // catch {}
  382. // }
  383. }
  384. public void AddRange (int range)
  385. {
  386. AddRange ("bytes", range);
  387. }
  388. public void AddRange (int from, int to)
  389. {
  390. AddRange ("bytes", from, to);
  391. }
  392. public void AddRange (string rangeSpecifier, int range)
  393. {
  394. if (rangeSpecifier == null)
  395. throw new ArgumentNullException ("rangeSpecifier");
  396. string value = Headers ["Range"];
  397. if (value == null || value.Length == 0)
  398. value = rangeSpecifier + "=";
  399. else if (value.StartsWith (rangeSpecifier.ToLower () + "=", StringComparison.InvariantCultureIgnoreCase))
  400. value += ",";
  401. else
  402. throw new InvalidOperationException ("rangeSpecifier");
  403. Headers.RemoveAndAdd ("Range", value + range + "-");
  404. }
  405. public void AddRange (string rangeSpecifier, int from, int to)
  406. {
  407. if (rangeSpecifier == null)
  408. throw new ArgumentNullException ("rangeSpecifier");
  409. if (from < 0 || to < 0 || from > to)
  410. throw new ArgumentOutOfRangeException ();
  411. string value = Headers ["Range"];
  412. if (value == null || value.Length == 0)
  413. value = rangeSpecifier + "=";
  414. else if (value.StartsWith (rangeSpecifier.ToLower () + "=", StringComparison.InvariantCultureIgnoreCase))
  415. value += ",";
  416. else
  417. throw new InvalidOperationException ("rangeSpecifier");
  418. Headers.RemoveAndAdd ("Range", value + from + "-" + to);
  419. }
  420. public override Stream GetRequestStream()
  421. {
  422. return _provider.GetRequestStream();
  423. // lock(this)
  424. // {
  425. // Type t = Type.GetType("System.IO.ConsoleWriteStream", true);
  426. // _connection.setDoOutput(true);
  427. //
  428. //
  429. //// Console.WriteLine("Request is sent with following headers:");
  430. //// java.util.Map map = _connection.getRequestProperties();
  431. //// for(java.util.Iterator iter = map.keySet().iterator(); iter.hasNext();)
  432. //// {
  433. //// string key = (string) iter.next();
  434. //// Console.WriteLine(key + ": " + map.get(key));
  435. //// }
  436. //
  437. // foreach(string k in Headers)
  438. // {
  439. // string val = Headers[k];
  440. // val = (val == null) ? "" : val;
  441. // _connection.setRequestProperty(k, val);
  442. // }
  443. //
  444. // _writeStream = (Stream) Activator.CreateInstance(t, new object[]{_connection.getOutputStream()});
  445. // _haveRequest = true;
  446. // return _writeStream;
  447. // }
  448. }
  449. public override WebResponse GetResponse()
  450. {
  451. return _provider.GetResponse();
  452. }
  453. /*
  454. private void CommonChecks (bool putpost)
  455. {
  456. string method = _connection.getRequestMethod();
  457. if (method == null)
  458. throw new ProtocolViolationException ("Method is null.");
  459. bool keepAlive = _headers["Keep-Alive"] == null;
  460. bool allowBuffering = true;
  461. bool sendChunked = true;
  462. long contentLength = _connection.getContentLength();
  463. if (putpost && ((!keepAlive || (contentLength == -1 && !sendChunked)) && !allowBuffering))
  464. throw new ProtocolViolationException ("Content-Length not set");
  465. string transferEncoding = TransferEncoding;
  466. if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
  467. throw new ProtocolViolationException ("SendChunked should be true.");
  468. }
  469. */
  470. public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
  471. {
  472. return _provider.BeginGetRequestStream(callback, state);
  473. }
  474. public override Stream EndGetRequestStream(IAsyncResult asyncResult)
  475. {
  476. return _provider.EndGetRequestStream(asyncResult);
  477. }
  478. public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
  479. {
  480. //todo check input, http headers etc.
  481. return _provider.BeginGetResponse(callback, state);
  482. }
  483. public override WebResponse EndGetResponse(IAsyncResult asyncResult)
  484. {
  485. return _provider.EndGetResponse(asyncResult);
  486. }
  487. #endregion
  488. #region Inner Classes
  489. // #region JavaHeaders class
  490. // [Serializable]
  491. // internal sealed class JavaHeaders : WebHeaderCollection
  492. // {
  493. // private java.net.HttpURLConnection _connection;
  494. //
  495. // internal JavaHeaders(java.net.HttpURLConnection con)
  496. // {
  497. // _connection = con;
  498. // }
  499. //
  500. // public string this[string key]
  501. // {
  502. // get
  503. // {
  504. // return _connection.getHeaderField(key);
  505. // }
  506. // set
  507. // {
  508. // _connection.addRequestProperty(key, value);
  509. // }
  510. // }
  511. // }
  512. // #endregion
  513. #endregion
  514. }
  515. }