internal HttpWebRequest(System.Net.HttpWebRequest webRequest) : base(webRequest) { if (webRequest == null) throw new ArgumentNullException("webRequest"); _webRequest = webRequest; }
protected override void AppendOAuthInfo( HttpWebRequest webRequest, Dictionary< string, string > query, string token, string tokenSecret ) { var realm = this.Realm.Scheme + "://" + this.Realm.Host + this.Realm.AbsolutePath; var credential = OAuthUtility.CreateAuthorization( HttpConnection.GetMethod, this.ServiceProvider, query, this.consumerKey, this.consumerSecret, token, tokenSecret, realm ); webRequest.Headers.Add( "X-Verify-Credentials-Authorization", credential ); webRequest.Headers.Add( "X-Auth-Service-Provider", string.Format("{0}://{1}{2}", this.ServiceProvider.Scheme, this.ServiceProvider.Host, this.ServiceProvider.AbsolutePath)); }
private void RequestFilter(System.Net.HttpWebRequest request) { request.UserAgent = "WooCommerce.NET"; string jsonString = JsonConvert.SerializeObject(request, Formatting.Indented); TraceRequest(jsonString); /* * "Method: " + request.Method + Environment.NewLine + * "AbsoluteUri: " + request.RequestUri.AbsoluteUri + Environment.NewLine + * "OriginalString: " + request.RequestUri.OriginalString + Environment.NewLine + * "ReadWriteTimeout: " + request.ReadWriteTimeout + Environment.NewLine + * "Timeout: " + request.Timeout + Environment.NewLine * );*/ }
public override System.Net.HttpWebRequest PrepareWebRequest(System.Net.HttpWebRequest webRequest) { webRequest = base.PrepareWebRequest(webRequest); webRequest.ContentType = "application/json"; //Get from MimeType? webRequest.MediaType = "UTF-8"; var bytes = ModelToSend.ToJsonBytes(); webRequest.ContentLength = bytes.Length; var stream = webRequest.GetRequestStream(); stream.Write(bytes, 0, bytes.Length); stream.Close(); return(webRequest); }
static void Main(string[] args) { System.Net.HttpWebRequest Request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create( "http://localhost/Chapter9/MovieService.svc/Films(1)" ); Request.Method = "GET"; Request.Accept = "application/json"; System.Net.HttpWebResponse Response = (System.Net.HttpWebResponse)Request.GetResponse(); using (System.IO.StreamReader sr = new System.IO.StreamReader(Response.GetResponseStream())) { Console.WriteLine(sr.ReadToEnd()); } Console.ReadKey(); }
private void requestCompleted(IAsyncResult asyncResult) { if (asyncResult == null) { return; } System.Net.HttpWebRequest hwr = asyncResult.AsyncState as System.Net.HttpWebRequest; System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)hwr.EndGetResponse(asyncResult); System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream()); textBox1.Text = sr.ReadToEnd(); }
public static Image PUGGetCompoundImage(string smiles, string casNo) { string imageReference = "http://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/" + casNo + "/PNG"; System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(imageReference); try { System.Net.WebResponse response = request.GetResponse(); return(Image.FromStream(response.GetResponseStream())); } catch (System.Exception p_Ex) { return(null);// Properties.Resources.Image1; } }
protected static System.Net.HttpWebRequest CreateRequest(string url, string useragent) { try { System.Net.HttpWebRequest req = System.Net.WebRequest.Create(url) as System.Net.HttpWebRequest; if (req != null) { req.UserAgent = useragent; } return(req); } catch (System.Security.SecurityException e) { //System.Windows.Forms.MessageBox.Show( "アクセス許可がありません" ); return(null); } }
private void Button_Click(object sender, RoutedEventArgs e) { System.Net.HttpWebRequest wr = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://yahoo.co.jp"); wr.Method = "GET"; System.Net.WebResponse res = wr.GetResponse(); System.IO.Stream rs = res.GetResponseStream(); wb.NavigateToStream(rs); //wb.Source = rs; //wb.Navigate("https://www.msn.com/ja-jp"); }
protected Image FetchPictureFromWeb(string url) { try { System.Net.HttpWebRequest httpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url); System.Net.HttpWebResponse httpWebReponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse(); System.IO.Stream stream = httpWebReponse.GetResponseStream(); return(Image.FromStream(stream)); } catch (Exception) { return(Properties.GlobalResources.vmoso_login); } }
public void CreateFolder() { System.Net.HttpWebRequest req = CreateRequest(""); req.Method = System.Net.WebRequestMethods.Http.MkCol; req.KeepAlive = false; Utility.AsyncHttpRequest areq = new Utility.AsyncHttpRequest(req); using (System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)areq.GetResponse()) { int code = (int)resp.StatusCode; if (code < 200 || code >= 300) //For some reason Mono does not throw this automatically { throw new System.Net.WebException(resp.StatusDescription, null, System.Net.WebExceptionStatus.ProtocolError, resp); } } }
/// <summary> /// @brief 将指定的二进制数据放在request中Post到指定的uri中 /// @return /// 非null:已二进制数组方式返回response body中的数据 /// null:response body没有返回数据 /// </summary> /// <param name="uri"></param> /// <param name="requestData"></param> /// <param name="keepAlive"> /// true:Connection:Keep-Alive /// false:Connection:Close /// </param> /// <returns></returns> public static byte[] PostHttpRequest(string uri, byte[] requestData, bool keepAlive = false) { if (string.IsNullOrEmpty(uri) || requestData == null || requestData.Length < 1) { throw new Exception("uri\requestData must not be null"); } System.Net.HttpWebRequest request = null; byte[] ret = null; try { request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri); request.Method = "POST"; request.KeepAlive = keepAlive; request.ContentType = "application/octet-stream"; request.ServicePoint.Expect100Continue = false; request.UserAgent = "WLLibrary"; request.ContentLength = requestData.Length; System.IO.Stream streamRequest = request.GetRequestStream(); streamRequest.Write(requestData, 0, requestData.Length); streamRequest.Close(); //回复 System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); System.IO.Stream responseStream = response.GetResponseStream(); BinaryReader binaryReader = new BinaryReader(responseStream); if (response.ContentLength > 0) { ret = new byte[response.ContentLength]; responseStream.Read(ret, 0, ret.Length); } responseStream.Close(); response.Close(); } catch (Exception ex) { LogEngine.Write(LOGTYPE.ERROR, "PostHttpRequest:", ex.ToString()); } finally { if (request != null) { request.Abort(); } } return(ret); }
public static void ResumeRetry(string Url) { bool UseProxy = true; string ProxyServer = ""; int ProxyPort = 8080; string ProxyUsername = ""; string ProxyPassword = ""; System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(Url); if (UseProxy) { request.Proxy = new System.Net.WebProxy(ProxyServer + ":" + ProxyPort.ToString()); if (ProxyUsername.Length > 0) { request.Proxy.Credentials = new System.Net.NetworkCredential(ProxyUsername, ProxyPassword); } } byte[] ba = System.IO.File.ReadAllBytes("partial"); int BytesRead = ba.Length; bool resuming = false; //HttpWebRequest hrequest = (HttpWebRequest)request; //hrequest.AddRange(BytesRead); ::TODO: Work on this if (BytesRead > 0) { resuming = true; request.AddRange(BytesRead); } System.Net.WebResponse response = request.GetResponse(); //result.MimeType = response.ContentType; //result.LastModified = response.LastModified; if (!resuming)//(Size == 0) { //resuming = false; int Size = (int)response.ContentLength; int SizeInKB = (int)Size / 1024; } bool acceptRanges = string.Compare(response.Headers["Accept-Ranges"], "bytes", true) == 0; // Create network stream System.IO.Stream ns = response.GetResponseStream(); }
public MessageBase DownLoad(string directoryPath, string fileName) { if (string.IsNullOrEmpty(_url)) { return(new MessageBase(0, "Ilegal download_url ,null or empty")); } try { System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(_url); request.ContentType = "application/octet-stream"; request.Method = "GET"; System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); //Get Extensison string extensison = response.Headers["Content-Disposition"]; var tempArry = Regex.Split(extensison, "filename=", RegexOptions.IgnoreCase)[1].Split('.'); extensison = "." + tempArry[tempArry.Length - 1]; var filesavePath = Path.Combine(directoryPath, fileName + extensison); BinaryWriter bw = new BinaryWriter(File.Create(filesavePath)); using (System.IO.Stream responseStream = response.GetResponseStream()) { //将基础流写入内存流 MemoryStream memoryStream = new MemoryStream(); const int bufferLength = 1024; int actual; byte[] buffer = new byte[bufferLength]; //while ((actual = responseStream.Read(buffer, 0, bufferLength)) > 0) //{ // memoryStream.Write(buffer, 0, actual); //} //memoryStream.Position = 0; //byte[] byt = new byte[memoryStream.Length]; //memoryStream.Read(byt, 0, byt.Length); //memoryStream.Seek(0, SeekOrigin.Begin); //bw.Write(buffer, 0, actual); //bw.Close(); while ((actual = responseStream.Read(buffer, 0, bufferLength)) > 0) { bw.Write(buffer, 0, actual); } bw.Close(); return(new MessageBase(1, "Download Success!Path is " + filesavePath)); } } catch (Exception ex) { return(new MessageBase(0, ex.Message)); } }
/// <summary> /// Fetches Mozscape API results, returns a string /// </summary> /// <param name="strAPIURL"></param> public string FetchResults(string strAPIURL) { string strResults = ""; // Used to build output StringBuilder sb = new StringBuilder(); byte[] buf = new byte[8192]; // Create web request using the Mozscape API URL System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(strAPIURL); // Execute the request try { // Get the response from the API System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); // Read data via the response stream System.IO.Stream resStream = response.GetResponseStream(); string tempString = null; int count = 0; // Read the stream into a buffer and build our results string do { // Fill the buffer with data count = resStream.Read(buf, 0, buf.Length); // Make sure we read some data if (count != 0) { // Translate from bytes to ASCII text tempString = Encoding.ASCII.GetString(buf, 0, count); // Continue building the string sb.Append(tempString); } }while (count > 0); // Any more data to read? } catch (Exception error) { MessageBox.Show(error.Message); } strResults = sb.ToString(); return(strResults); }
public Form1() { InitializeComponent(); //HttpWebRequestを作成 System.Net.HttpWebRequest webreq = (System.Net.HttpWebRequest) System.Net.WebRequest.Create("https://matome.naver.jp/odai/2141253870948308001"); //サーバーからの応答を受信するためのHttpWebResponseを取得 System.Net.HttpWebResponse webres = (System.Net.HttpWebResponse)webreq.GetResponse(); //応答データを受信するためのStreamを取得 System.IO.Stream st = webres.GetResponseStream(); //文字コードを指定して、StreamReaderを作成 System.IO.StreamReader sr = new System.IO.StreamReader(st, System.Text.Encoding.UTF8); //データをすべて受信 string htmlSource = sr.ReadToEnd(); //閉じる sr.Close(); st.Close(); webres.Close(); //取得したソースを表示する List <string> imageUrl = new List <string>(); htmlSource = htmlSource.Trim('\n'); var matches = Regex.Matches(htmlSource, "<img src=\"[^\"]*\""); foreach (Match reg in matches) { var str = reg.Value; imageUrl.Add(str.Substring(10, str.Length - 1 - 10)); } matches = Regex.Matches(htmlSource, "image: url([^)]*)"); foreach (Match reg in matches) { var str = reg.Value; imageUrl.Add(str.Substring(11, str.Length - 1 - 10)); } SetImage(imageUrl.ToArray()); }
public static async Task AddImageFromUrl(string url, string imageName) { System.Net.HttpWebRequest request = null; byte[] b = null; name = imageName; request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); request.Method = "GET"; using (var response = (System.Net.HttpWebResponse) await request.GetResponseAsync()) { if (request.HaveResponse) { if (response.StatusCode == System.Net.HttpStatusCode.OK) { System.IO.Stream receiveStream = response.GetResponseStream(); using (System.IO.BinaryReader br = new System.IO.BinaryReader(receiveStream)) { b = br.ReadBytes(500000); if (b != null) { if (!Images.ContainsKey(name)) { // hold image byte[] image = new byte[b.Length]; image = b; Images.Add(imageName, b); // Debug.WriteLine("MAP SIZE: " + getImages.Count); b = null; } } br.Dispose(); } } } } }
/// <summary> /// 创建HttpWebResponse请求对象 /// </summary> /// <param name="url">请求网址</param> /// <param name="method">请求动作</param> /// <param name="postData">POST数据</param> /// <returns></returns> private System.Net.HttpWebResponse HttpWebResponse(string url, string postData = "", string name = "", string filePath = "") { try { System.Net.HttpWebRequest hwr = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); hwr.Timeout = Timeout; hwr.Method = Method.ToString(); if (Method.ToString().ToUpper() == "POST") { if (ContentType.ToString().ToUpper() == "DATA") { //POST 文件 string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线 byte[] item_boundary_bytes = Encoding.UTF8.GetBytes(string.Format("\r\n--{0}\r\n", boundary)); // 开始boundary byte[] post_header_bytes = Encoding.UTF8.GetBytes(StringBuilderHeader(name, filePath)); // 头部boundary byte[] file_bytes = FileBytes(filePath); // 文件byte byte[] post_data = StrToByte(postData); // 内容byte byte[] end_boundary_bytes = Encoding.UTF8.GetBytes(string.Format("\r\n--{0}--\r\n", boundary)); // 结束boundary hwr.ContentType = string.Format("multipart/form-data;charset=utf-8;boundary={0}", boundary); System.IO.Stream post_stream = hwr.GetRequestStream(); post_stream.Write(item_boundary_bytes, 0, item_boundary_bytes.Length); post_stream.Write(post_header_bytes, 0, post_header_bytes.Length); post_stream.Write(file_bytes, 0, file_bytes.Length); post_stream.Write(post_data, 0, post_data.Length); post_stream.Write(end_boundary_bytes, 0, end_boundary_bytes.Length); post_stream.Close(); } else { //POST 字符串 byte[] post_data = StrToByte(postData); hwr.ContentType = GetContentType(ContentType); hwr.ContentLength = post_data.Length; System.IO.Stream newStream = hwr.GetRequestStream(); newStream.Write(post_data, 0, post_data.Length); //设置POST newStream.Close(); } } System.Net.HttpWebResponse hwrs = (System.Net.HttpWebResponse)hwr.GetResponse(); return(hwrs); } catch (Exception ex) { throw new Exception(ex.Message); } }
public System.IO.Stream DownloadStream(string url) { InitiateSSLTrust(); //Create a WebRequest to get the file System.Net.HttpWebRequest fileReq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url); //Create a response for this request System.Net.HttpWebResponse fileResp = (System.Net.HttpWebResponse)fileReq.GetResponse(); // if (fileReq.ContentLength > 0) fileResp.ContentLength = fileReq.ContentLength; //Get the Stream returned from the response System.IO.Stream strm = fileResp.GetResponseStream(); return(strm); }
protected void Application_End() { NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger(); _logger.Log(NLog.LogLevel.Info, "C10Mvc Application_End()"); System.Threading.Thread.Sleep(3000); string sUrl = "http://localhost/C10Mvc/StockApi/getStockType?StockCode=1475"; System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(sUrl); System.Net.HttpWebResponse res = (System.Net.HttpWebResponse)req.GetResponse(); string desc = res.StatusDescription; _logger.Log(NLog.LogLevel.Info, "C10Mvc Application_End(), Application Restart....." + desc); }
private void makePictures(int i_AmountOfPairsInGame) { ////Gets Amount of pairs in game ////Create an Araay of String, and Puts a random Image URL string in each cell m_Pictures = new string[i_AmountOfPairsInGame]; string ImgUrl = string.Empty; for (int i = 0; i < i_AmountOfPairsInGame; i++) { System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://picsum.photos/80"); System.Net.HttpWebResponse myResp = (System.Net.HttpWebResponse)req.GetResponse(); m_Pictures[i] = myResp.ResponseUri.ToString(); myResp.Close(); } }
private bool CheckConnection(string URL) { try { System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(URL); request.Timeout = 5000; request.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials; System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); return(response.StatusCode == System.Net.HttpStatusCode.OK); } catch { return(false); } }
async Task <DTOs.Response.BootstrapResponse> scrapeFromUrl(string url) { System.Net.HttpWebRequest r = System.Net.HttpWebRequest.CreateHttp(url); var response = await r.GetResponseAsync(); try { string s = (new System.IO.StreamReader(response.GetResponseStream())).ReadToEnd(); return(Newtonsoft.Json.JsonConvert.DeserializeObject <DTOs.Response.BootstrapResponse>(s)); } catch { return(new DTOs.Response.BootstrapResponse()); } throw new NotImplementedException(); }
protected void Application_End(object sender, EventArgs e) { //Application_End其他代码 try { System.Threading.Thread.Sleep(5000); string strUrl = "http://192.9.190.197:8080/"; System.Net.HttpWebRequest _HttpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(strUrl); System.Net.HttpWebResponse _HttpWebResponse = (System.Net.HttpWebResponse)_HttpWebRequest.GetResponse(); System.IO.Stream _Stream = _HttpWebResponse.GetResponseStream();//得到回写的字节流 } catch (Exception ex) { LogHelper.WriteLog(this.GetType(), ex); } }
void Session_End(object sender, EventArgs e) { //这里设置你的web地址,可以随便指向你的任意一个aspx页面甚至不存在的页面,目的是要激发Application_Start //使用您自己的URL string url = "http://localhost"; System.Net.HttpWebRequest myHttpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); System.Net.HttpWebResponse myHttpWebResponse = (System.Net.HttpWebResponse)myHttpWebRequest.GetResponse(); System.IO.Stream receiveStream = myHttpWebResponse.GetResponseStream();//得到回写的字节流 // 在会话结束时运行的代码。 // 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为 InProc 时,才会引发 Session_End 事件。 // 如果会话模式设置为 StateServer 或 SQLServer,则不会引发该事件。 }
private string GetAlternateLocations(string locationName) { try { System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(String.Format(ConfigurationManager.AppSettings["GeocodeUrl"], locationName)); req.Method = "GET"; req.Timeout = 15000; System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)req.GetResponse(); System.IO.StreamReader reader = new System.IO.StreamReader((System.IO.Stream)resp.GetResponseStream()); return(reader.ReadToEnd()); } catch { return(null); } }
public static bool JudgeFileExist(string url) { try { //创建根据网络地址的请求对象 System.Net.HttpWebRequest httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.CreateDefault(new Uri(url)); httpWebRequest.Method = "HEAD"; httpWebRequest.Timeout = 1000; //返回响应状态是否是成功比较的布尔值 return(((System.Net.HttpWebResponse)httpWebRequest.GetResponse()).StatusCode == System.Net.HttpStatusCode.OK); } catch { return(false); } }
public static bool UrlExistsUsingHttpWebRequest(string url) { try { System.Net.HttpWebRequest myRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); myRequest.Method = "HEAD"; myRequest.Timeout = 100; System.Net.HttpWebResponse res = (System.Net.HttpWebResponse)myRequest.GetResponse(); return(res.StatusCode == System.Net.HttpStatusCode.OK); } catch (System.Net.WebException we) { System.Diagnostics.Trace.Write(we.Message); return(false); } }
public override void ApplyAuthenticationToHostRequest(System.Net.HttpWebRequest request, bool forAccessingUser) { Telligent.Evolution.Extensibility.OAuthClient.Version1.User user = null; if (forAccessingUser) { user = GetAccessingUser(); } if (user == null) { user = Telligent.Evolution.Extensibility.OAuthClient.Version1.OAuthAuthentication.GetDefaultUser(this.Id); } Telligent.Evolution.Extensibility.OAuthClient.Version1.OAuthAuthentication.ApplyAuthenticationToRequest(this.Id, user, request); }
protected void Application_End() { // 在应用程序关闭时运行的代码 //如果出错,删除下面代码 //下面的代码是关键,可解决IIS应用程序池自动回收的问题 System.Threading.Thread.Sleep(1000); ////这里设置你的web地址,可以随便指向你的任意一个aspx页面甚至不存在的页面,目的是要激发Application_Start ////string url = "http://www.xxxxx.com"; string url = "http://localhost:82/111.aspx"; System.Net.HttpWebRequest myHttpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); System.Net.HttpWebResponse myHttpWebResponse = (System.Net.HttpWebResponse)myHttpWebRequest.GetResponse(); System.IO.Stream receiveStream = myHttpWebResponse.GetResponseStream();//得到回写的字节流 //在此添加其它代码 }
public bool GetInformation() { try { String sURL = String.Empty; sURL = "http://" + _ApplicationSettings.WebServerIP + ":" + _ApplicationSettings.WebServerDataCollectionPort + "/" + "uccxrealtimedata" + "?operation=systemstatus"; Trace.TraceInformation("sURL = " + sURL); System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(sURL); System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); Trace.TraceInformation("Content type is {0} and length is {1}", response.ContentType, response.ContentLength); System.IO.Stream stream = response.GetResponseStream(); // Pipes the stream to a higher level stream reader with the required encoding format. System.IO.StreamReader streamReader = new System.IO.StreamReader(stream, Encoding.UTF8); String sResponse = streamReader.ReadToEnd(); streamReader.Close(); streamReader.Dispose(); streamReader = null; stream.Close(); stream.Dispose(); stream = null; response.Close(); response = null; request = null; xmlDoc = new XmlDocument(); xmlDoc.LoadXml(sResponse); return(true); } catch (Exception ex) { Trace.TraceError("Exception:" + ex.Message + Environment.NewLine + "StackTrace:" + ex.StackTrace); return(false); } }
public static async System.Threading.Tasks.Task <System.Collections.Generic.List <Models.Expo> > FetchUserExposAsync(Models.User u) { // Create an HTTP web request using the URL: System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(new Uri(url1 + "UserExpos?email=" + u.Email)); request.ContentType = "application/json"; request.Method = "GET"; // Send the request to the server and wait for the response: using (System.Net.WebResponse response = await request.GetResponseAsync()) { // Get a stream representation of the HTTP web response: using (Stream stream = response.GetResponseStream()) { // Use this stream to build a JSON document object: System.Json.JsonValue jsonDoc = await System.Threading.Tasks.Task.Run(() => System.Json.JsonObject.Load(stream)); Console.Out.WriteLine("Response: {0}", jsonDoc.ToString()); // Return the JSON document: System.Collections.Generic.List <Models.Expo> lista = new System.Collections.Generic.List <Models.Expo>(); for (int i = 0; i != jsonDoc.Count; i++) { Models.Expo e = new Models.Expo { Name_Expo = jsonDoc[i]["Name_Expo"], Id = Int32.Parse(jsonDoc[i]["Id"].ToString()), Photo = jsonDoc[i]["Photo"], MapPhoto = jsonDoc[i]["MapPhoto"], Adres = jsonDoc[i]["Adres"], Description = jsonDoc[i]["Description"] }; var start = double.Parse(jsonDoc[i]["ExpoStartData"].ToString().Replace('/', ' ').Replace('"', ' ').Replace(')', ' ').Replace("Date(", "").Trim()); TimeSpan time = TimeSpan.FromMilliseconds(start); DateTime startdate = new DateTime(1970, 1, 1) + time; e.DataTargowStart = startdate; var end = double.Parse(jsonDoc[i]["ExpoEndData"].ToString().Replace('/', ' ').Replace('"', ' ').Replace(')', ' ').Replace("Date(", "").Trim()); TimeSpan time1 = TimeSpan.FromMilliseconds(end); DateTime enddate = new DateTime(1970, 1, 1) + time1; e.DataTargowEnd = enddate; lista.Add(e); } return(lista); } } }
protected override void AppendOAuthInfo(HttpWebRequest webRequest, Dictionary< string, string > query, string token, string tokenSecret) { // OAuth共通情報取得 Dictionary< string, string > parameter = this.GetOAuthParameter( token ); // OAuth共通情報にquery情報を追加 if ( query != null ) foreach ( KeyValuePair< string, string > item in query ) parameter.Add( item.Key, item.Value ); // 署名の作成・追加(GETメソッド固定。ServiceProvider呼び出し用の署名作成) parameter.Add( "oauth_signature", this.CreateSignature( tokenSecret, HttpConnection.GetMethod, this._serviceProvider, parameter ) ); // HTTPリクエストのヘッダに追加 StringBuilder sb = new StringBuilder ("OAuth "); sb.AppendFormat( "realm=\"{0}://{1}{2}\",", this._realm.Scheme, this._realm.Host, this._realm.AbsolutePath ); foreach ( KeyValuePair< string, string > item in parameter ) if ( item.Key.StartsWith( "oauth_" ) ) sb.AppendFormat( "{0}=\"{1}\",", item.Key, this.UrlEncode( item.Value ) ); webRequest.Headers.Add( "X-Verify-Credentials-Authorization", sb.ToString() ); webRequest.Headers.Add( "X-Auth-Service-Provider", string.Format( "{0}://{1}{2}", this._serviceProvider.Scheme, this._serviceProvider.Host, this._serviceProvider.AbsolutePath ) ); }
/// <summary> /// Creates a new default http webrequest. /// </summary> /// <param name="url"></param> public HttpWebRequestDefault(string url) { _httpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url); }
/// <summary> /// 下载图片 /// </summary> public void DownloadImg() { if (PreFetcher.Fetcher.PreFetchedImg(img.PreviewUrl) != null) { preview.Source = PreFetcher.Fetcher.PreFetchedImg(img.PreviewUrl); //preview.Source = BitmapDecoder.Create(PreFetcher.Fetcher.PreFetchedImg(img.PreUrl), BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames[0]; } else { try { req = System.Net.WebRequest.Create(img.PreviewUrl) as System.Net.HttpWebRequest; req.Proxy = MainWindow.WebProxy; req.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"; if (needReferer != null) //req.Referer = img.PreUrl.Substring(0, img.PreUrl.IndexOf('/', 7) + 1); req.Referer = needReferer; //异步下载开始 req.BeginGetResponse(new AsyncCallback(RespCallback), req); } catch (Exception ex) { Program.Log(ex, "Start download preview failed"); StopLoadImg(); } } if (!isDetailSucc && img.DownloadDetail != null) { isRetrievingDetail = true; chk.Text = "信息加载中..."; System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback((o) => { try { img.DownloadDetail(img, MainWindow.WebProxy); Dispatcher.Invoke(new VoidDel(() => { LayoutRoot.IsEnabled = true; ShowImgDetail(); isRetrievingDetail = false; if (imgLoaded && ImgLoaded != null) ImgLoaded(index, null); })); } catch (Exception ex) { Program.Log(ex, "Download img detail failed"); Dispatcher.Invoke(new VoidDel(() => { isRetrievingDetail = false; canRetry = true; chk.Text = "信息加载失败"; if (imgLoaded && ImgLoaded != null) ImgLoaded(index, null); })); } })); } }
/// <summary> /// HTTPリクエストにOAuth関連ヘッダを追加 /// </summary> /// <param name="webRequest">追加対象のHTTPリクエスト</param> /// <param name="query">OAuth追加情報+クエリ or POSTデータ</param> /// <param name="token">アクセストークン、もしくはリクエストトークン。未取得なら空文字列</param> /// <param name="tokenSecret">アクセストークンシークレット。認証処理では空文字列</param> protected virtual void AppendOAuthInfo( HttpWebRequest webRequest, Dictionary< string, string > query, string token, string tokenSecret ) { // OAuth共通情報取得 Dictionary< string, string > parameter = this.GetOAuthParameter( token ); // OAuth共通情報にquery情報を追加 if ( query != null ) foreach ( KeyValuePair< string, string > item in query ) parameter.Add( item.Key, item.Value ); // 署名の作成・追加 parameter.Add( "oauth_signature", this.CreateSignature( tokenSecret, webRequest.Method, webRequest.RequestUri, parameter ) ); // HTTPリクエストのヘッダに追加 StringBuilder sb = new StringBuilder( "OAuth " ); foreach ( KeyValuePair< string, string > item in parameter ) // 各種情報のうち、oauth_で始まる情報のみ、ヘッダに追加する。各情報はカンマ区切り、データはダブルクォーテーションで括る if ( item.Key.StartsWith("oauth_") ) sb.AppendFormat( "{0}=\"{1}\",", item.Key, this.UrlEncode( item.Value ) ); webRequest.Headers.Add( HttpRequestHeader.Authorization, sb.ToString() ); }
public void RequestAbort() { try { if ( this.streamReq != null ) { this.streamReq.Abort(); this.streamReq = null; } } catch ( Exception ) {} }
private String PerformRequest(String method, String url, String data) { if ((method.CompareTo("GET") == 0) && (!String.IsNullOrEmpty(data))) { if (url.Contains("?")) { url = url + "&"; } else { url = url + "?"; } url = url + data; } //Create connection connection = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); connection.UserAgent = "Veridu-CSharp/" + sdkVersion; connection.Headers.Add("Veridu-Client", this.clientId); if (!String.IsNullOrEmpty(this.sessionToken)) { connection.Headers.Add("Veridu-Session", this.sessionToken); } connection.Method = method; connection.Timeout = 10000; connection.ReadWriteTimeout = 10000; connection.ContentType = "application/x-www-form-urlencoded"; //Send request if (!String.IsNullOrWhiteSpace(data) && !method.Contains("GET")) { UTF8Encoding encoding = new UTF8Encoding(); byte[] bytes = encoding.GetBytes(data); connection.ContentLength = bytes.Length; using (System.IO.Stream dataStream = connection.GetRequestStream()) { dataStream.Write(bytes, 0, bytes.Length); } } else { connection.ContentLength = 0; } //Get Response string result = ""; try { using (System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)connection.GetResponse()) { System.Net.HttpStatusCode status = response.StatusCode; System.IO.Stream receiveStream = response.GetResponseStream(); System.IO.StreamReader sr = new System.IO.StreamReader(receiveStream); result = sr.ReadToEnd().Trim(); } } catch (Exception ex) { System.Net.WebException wex = (System.Net.WebException)ex; var s = wex.Response.GetResponseStream(); result = ""; int lastNum = 0; do { lastNum = s.ReadByte(); result += (char)lastNum; } while (lastNum != -1); s.Close(); s = null; } return result; }
public ClientHttpWebRequest(Uri requestUri) { Debug.Assert(requestUri != null, "requestUri can't be null."); this.innerRequest = (System.Net.HttpWebRequest)System.Net.Browser.WebRequestCreator.ClientHttp.Create(requestUri); Debug.Assert(this.innerRequest != null, "ClientHttp.Create failed to create a new request without throwing exception."); }
/// <summary> /// Creates a new default http webrequest. /// </summary> /// <param name="url"></param> public NativeHttpWebRequest(string url) { _httpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url); }
private string sendRequest(string req_xml, System.ComponentModel.BackgroundWorker bw) { int counter = 0; string ret = "Unknown Error"; XmlDocument soap_env = new XmlDocument(); soap_env.LoadXml(req_xml); request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); request.Headers.Add("SOAPAction", soap_action); request.ContentType = "text/xml;charset=\"utf-8\""; request.Method = "POST"; request.CookieContainer = cookie; request.KeepAlive = false; //true request.UserAgent = "Small Craft C#"; // Ignore SSL Error if using https System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate( Object obj, X509Certificate certificate, X509Chain chain, System.Net.Security.SslPolicyErrors errors) { return (true); }; Stream stream = request.GetRequestStream(); soap_env.Save(stream); try { string buf = ""; System.Net.WebResponse response = request.GetResponse(); Stream s = response.GetResponseStream(); StreamReader sr = new StreamReader(s); while (!sr.EndOfStream) { buf += sr.ReadLine(); counter++; if (reportProgress) { bw.ReportProgress(counter); } } ret = buf; } catch (System.Net.WebException webExc) { ret = webExc.ToString(); } return ret; }
internal ClientWebHeaderCollection(System.Net.WebHeaderCollection collection, System.Net.HttpWebRequest request) { Debug.Assert(collection != null, "collection can't be null."); this.innerCollection = collection; this.request = request; }
/// <summary> /// HTTPリクエストにOAuth関連ヘッダを追加 /// </summary> /// <param name="webRequest">追加対象のHTTPリクエスト</param> /// <param name="query">OAuth追加情報+クエリ or POSTデータ</param> /// <param name="token">アクセストークン、もしくはリクエストトークン。未取得なら空文字列</param> /// <param name="tokenSecret">アクセストークンシークレット。認証処理では空文字列</param> protected virtual void AppendOAuthInfo( HttpWebRequest webRequest, Dictionary< string, string > query, string token, string tokenSecret ) { var credential = OAuthUtility.CreateAuthorization( webRequest.Method, webRequest.RequestUri, query, this.consumerKey, this.consumerSecret, token, tokenSecret ); webRequest.Headers.Add( HttpRequestHeader.Authorization, credential ); }
/// <summary> /// OAuth認証で指定のURLとHTTP通信を行い、ストリームを返す /// </summary> /// <param name="method">HTTP通信メソッド(GET/HEAD/POST/PUT/DELETE)</param> /// <param name="requestUri">通信先URI</param> /// <param name="param">GET時のクエリ、またはPOST時のエンティティボディ</param> /// <param name="content">[OUT]HTTP応答のボディストリーム</param> /// <returns>HTTP応答のステータスコード</returns> public HttpStatusCode GetContent( string method, Uri requestUri, Dictionary< string, string > param, ref Stream content, string userAgent ) { // 認証済かチェック if ( string.IsNullOrEmpty( token ) ) return HttpStatusCode.Unauthorized; this.RequestAbort(); this.streamReq = this.CreateRequest( method, requestUri, param, false ); // User-Agent指定がある場合は付加 if ( !string.IsNullOrEmpty( userAgent ) ) this.streamReq.UserAgent = userAgent; // OAuth認証ヘッダを付加 this.AppendOAuthInfo( this.streamReq, param, token, tokenSecret ); try { HttpWebResponse webRes = (HttpWebResponse)this.streamReq.GetResponse(); content = webRes.GetResponseStream(); return webRes.StatusCode; } catch ( WebException ex ) { if ( ex.Status == WebExceptionStatus.ProtocolError ) { HttpWebResponse res = (HttpWebResponse)ex.Response; return res.StatusCode; } throw; } }
Client(System.Net.HttpWebRequest request, System.Net.HttpWebResponse response) { this.request = request; this.response = response; this.Response = new Header.Response("HTTP/" + response.ProtocolVersion, (Status)(int)response.StatusCode, response.Headers.AllKeys.Map(key => KeyValue.Create(key, response.Headers[key]))); }
public bool Close() { bool result; if (result = this.request.NotNull()) { this.request.Abort(); this.request = null; } if (result |= this.response.NotNull()) { this.response.Close(); this.response = null; } return result; }