public void Request(string url) { Stopwatch timer = new Stopwatch(); StringBuilder respBody = new StringBuilder(); this.request = (HttpWebRequest)WebRequest.Create(url); try { timer.Start(); this.response = (HttpWebResponse)this.request.GetResponse(); byte[] buf = new byte[8192]; Stream respStream = this.response.GetResponseStream(); int count = 0; do { count = respStream.Read(buf, 0, buf.Length); if (count != 0) respBody.Append(Encoding.ASCII.GetString(buf, 0, count)); } while (count > 0); timer.Stop(); this.responseBody = respBody.ToString(); this.statusCode = (int)(HttpStatusCode)this.response.StatusCode; this.responseTime = timer.ElapsedMilliseconds / 1000.0; } catch (WebException ex) { this.response = (HttpWebResponse)ex.Response; this.responseBody = "No Server Response"; this.escapedBody = "No Server Response"; this.responseTime = 0.0; } }
private void set_option(string rel) { string url = "http://" + URI + "/web/cgi-bin/hi3510/param.cgi?"+rel+"&usr="******"&pwd=" + Password; Console.WriteLine("Call "+url+" - start"); HttpWebRequest req = (HttpWebRequest)WebRequest.Create (url); req.KeepAlive = false; req.Headers.Add ("Accept-Encoding", "gzip,deflate"); req.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; req.UseDefaultCredentials = true; req.Credentials = new NetworkCredential (Login, Password); req.Proxy = null; req.Timeout = 1000; WebResponse resp = null; req.KeepAlive = false; pause = true; try{ resp = req.GetResponse(); resp.Close(); } catch(Exception e) { Console.WriteLine (e.Message); } req = null; Console.WriteLine("Call "+url+" - end"); }
private void AddRequestXml(string url, HttpWebRequest req) { Stream stream = (Stream)req.GetRequestStream(); using (XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8)) { writer.WriteStartDocument(true); writer.WriteStartElement("methodCall"); writer.WriteElementString("methodName", "pingback.ping"); writer.WriteStartElement("params"); writer.WriteStartElement("param"); writer.WriteStartElement("value"); writer.WriteElementString("string", Blogsa.Url); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteStartElement("param"); writer.WriteStartElement("value"); writer.WriteElementString("string", url); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndElement(); } }
public RequestState() { BufferRead = new byte[BUFFER_SIZE]; requestData = new StringBuilder(""); request = null; streamResponse = null; }
public State (int id, HttpWebRequest req) { this.id = id; request = req; handle = new ManualResetEvent (false); handleList.Add (handle); }
// fields // constructors // properties // methods internal static void OnSendingHeaders(HttpWebRequest httpWebRequest) { GlobalLog.Print("CookieModule::OnSendingHeaders()"); try { if (httpWebRequest.CookieContainer == null) { return; } // // remove all current cookies. This could be a redirect // httpWebRequest.Headers.RemoveInternal(HttpKnownHeaderNames.Cookie); // // add in the new headers from the cookie container for this request // string optCookie2; string cookieString = httpWebRequest.CookieContainer.GetCookieHeader( httpWebRequest.GetRemoteResourceUri(), out optCookie2); if (cookieString.Length > 0) { GlobalLog.Print("CookieModule::OnSendingHeaders() setting Cookie header to:[" + cookieString + "]"); httpWebRequest.Headers[HttpKnownHeaderNames.Cookie] = cookieString; //< } } catch { } }
public OpenSocialHttpRequest(OpenSocialUrl url) { this.method = "GET"; this.postBody = null; this.connection = null; this.setUrl(url); }
internal static void OnReceivedHeaders(HttpWebRequest httpWebRequest) { GlobalLog.Print("CookieModule.OnReceivedHeaders()"); // // if the app doesn't want us to handle cookies then there's nothing // to do. Note that we're leaving open the possibility that these // settings could be changed between the request being made and the // response received // try { if (httpWebRequest.CookieContainer == null) { return; } // // add any received cookies for this response to the container // HttpWebResponse response = (HttpWebResponse)httpWebRequest._HttpResponse; CookieCollection cookies = null; try { string cookieString = response.Headers[HttpKnownHeaderNames.SetCookie]; GlobalLog.Print("CookieModule::OnSendingHeaders() received Set-Cookie:[" + cookieString + "]"); if ((cookieString != null) && (cookieString.Length > 0)) { cookies = httpWebRequest.CookieContainer.CookieCutter( response.ResponseUri, HttpKnownHeaderNames.SetCookie, cookieString, false); } } catch { } try { string cookieString = response.Headers[HttpKnownHeaderNames.SetCookie2]; GlobalLog.Print("CookieModule::OnSendingHeaders() received Set-Cookie2:[" + cookieString + "]"); if ((cookieString != null) && (cookieString.Length > 0)) { CookieCollection cookies2 = httpWebRequest.CookieContainer.CookieCutter( response.ResponseUri, HttpKnownHeaderNames.SetCookie2, cookieString, false); if (cookies != null && cookies.Count != 0) { cookies.Add(cookies2); } else { cookies = cookies2; } } } catch { } if (cookies != null) { response.Cookies = cookies; } } catch { } }
public static void InitializeRequest(HttpWebRequest request) { request.Headers.Add("aw-tenant-code", API_TENANT_CODE); request.Credentials = new NetworkCredential(USER_NAME, PASSWORD); request.KeepAlive = false; request.AddRange(1024); request.Timeout = 10000; }
protected HttpWebResponse getResponse(HttpWebRequest request) { // execute the request HttpWebResponse response = (HttpWebResponse) request.GetResponse(); return response; }
public void CreateNewConnection() { Dictionary<string, string> config = ConfigManager.Instance.GetProperties(); connectionMngr = ConnectionManager.Instance; httpRequest = connectionMngr.GetConnection(config, "http://paypal.com/"); Assert.IsNotNull(httpRequest); Assert.AreEqual("http://paypal.com/", httpRequest.RequestUri.AbsoluteUri); Assert.AreEqual(config["connectionTimeout"], httpRequest.Timeout.ToString()); }
/// <summary> /// For every request, there are things we expect to remain constant. Verify that they do. /// </summary> /// <param name="request"></param> /// <param name="method"></param> public void AssertRequestDefaults(HttpWebRequest request, string method) { Assert.IsTrue(request.Address == new Uri(host)); Assert.IsTrue(request.Headers.ToString() == "Authorization: Bearer\r\nContent-Type: application/json\r\n\r\n"); Assert.IsTrue(request.Host == "localhost"); Assert.IsTrue(request.KeepAlive == true); Assert.IsTrue(request.Method == method); Assert.IsTrue(request.Timeout == 90000); }
private void InitGCMClient() { //對GCM Server發出Http post gcmRequest = WebRequest.Create(GCM_URI) as HttpWebRequest; gcmRequest.ContentType = "application/json"; gcmRequest.UserAgent = "Android GCM Message Sender Client 1.0"; gcmRequest.Method = "POST"; // Credential info gcmRequest.Headers.Add("Authorization", "key=" + APIKey); }
/// <summary> /// Constructs a new async result object /// </summary> /// <param name="source">The source of the operation.</param> /// <param name="method">Name of the method which is invoked asynchronously.</param> /// <param name="request">The <see cref="HttpWebRequest"/> object which is wrapped by this async result.</param> /// <param name="callback">User specified callback for the async operation.</param> /// <param name="state">User state for the async callback.</param> internal GetReadStreamResult( object source, string method, HttpWebRequest request, AsyncCallback callback, object state) : base(source, method, callback, state) { Debug.Assert(request != null, "Null request can't be wrapped to a result."); this.request = request; this.Abortable = request; }
public Stream createDataStream(Dictionary<string,string> body ,HttpWebRequest request) { string theBody = ""; foreach(KeyValuePair<string,string> bodyPart in body){ theBody = theBody + bodyPart.Key + "=" + bodyPart.Value + "&"; } byte[] byteArray = Encoding.UTF8.GetBytes(theBody); request.ContentLength = byteArray.Length; Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0,byteArray.Length); dataStream.Close (); return dataStream; }
public static HttpWebRequest AddProxyInfoToRequest(HttpWebRequest httpRequest, Uri proxyUri, string proxyId, string proxyPassword, string proxyDomain) { if (httpRequest != null) { WebProxy proxyInfo = new WebProxy(); proxyInfo.Address = proxyUri; proxyInfo.BypassProxyOnLocal = true; proxyInfo.Credentials = new NetworkCredential(proxyId, proxyPassword, proxyDomain); httpRequest.Proxy = proxyInfo; } return httpRequest; }
public HttpWebRequestCore (HttpWebRequest parent, Uri uri) { if (uri == null) throw new ArgumentNullException ("uri"); this.uri = uri; if (parent == null) { // special case used for policy allow_read_buffering = true; method = "GET"; } else { allow_read_buffering = parent.AllowReadStreamBuffering; method = parent.Method; headers = parent.Headers; } }
/** * Initializes connection if necessary before establishing the connection, * including writing POST data to the connection's output stream if * applicable. * * @return HTTP status code of request, e.g. 200, 401, 500, etc. * @throws IOException */ public int execute() { if (this.connection == null) { this.connection = this.getConnection(); } this.connection.Method = method; if (this.postBody != null) { using (StreamWriter wr = new StreamWriter(this.connection.GetRequestStream())) { wr.Write(postBody); wr.Flush(); } } HttpWebResponse resp = (HttpWebResponse)connection.GetResponse(); return (int)resp.StatusCode; }
private string GetResponse(string url, ref HttpWebRequest request) { StringBuilder sb = new StringBuilder(); Stream resStream = null; HttpWebResponse response = null; byte[] buf = new byte[8192]; try { // execute the request response = (HttpWebResponse)request.GetResponse(); // we will read data via the response stream resStream = response.GetResponseStream(); string tempString = null; int count = 0; 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 err) { String exc = err.Message; } finally { response.Close(); resStream.Close(); } return sb.ToString(); }
/** * Constructs and returns the full URL associated with the passed request * object. * * @param request Servlet request object with methods for retrieving the * various components of the request URL */ public static String getRequestUrl(HttpWebRequest request) { StringBuilder requestUrl = new StringBuilder(); String scheme = request.RequestUri.Scheme; int port = request.RequestUri.Port; requestUrl.Append(scheme); requestUrl.Append("://"); requestUrl.Append(request.RequestUri.Host); if ((scheme.Equals("http") && port != 80) || (scheme.Equals("https") && port != 443)) { requestUrl.Append(":"); requestUrl.Append(port); } requestUrl.Append(request.RequestUri.AbsolutePath); // query string? return requestUrl.ToString(); }
public static void FillRequestWithContent(HttpWebRequest request, string contentPath) { using (BinaryReader reader = new BinaryReader(File.OpenRead(contentPath))) { request.ContentLength = reader.BaseStream.Length; using (Stream stream = request.GetRequestStream()) { byte[] buffer = new byte[reader.BaseStream.Length]; while (true) { int bytesRead = reader.Read(buffer, 0, buffer.Length); if (bytesRead == 0) { break; } stream.Write(buffer, 0, bytesRead); } } } }
public static string getResponce(HttpWebRequest request) { try { HttpWebResponse resp = (HttpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(resp.GetResponseStream()); string result = reader.ReadToEnd(); reader.Close(); return result + "&status=200"; } catch (Exception ex) { string statusCode = ""; if (ex.Message.Contains("403")) statusCode = "403"; else if (ex.Message.Contains("401")) statusCode = "401"; return string.Format("status={0}&error={1}", statusCode, ex.Message); } }
public BrowserHttpWebResponse (HttpWebRequest request, IntPtr native) { this.request = request; this.response = new MemoryStream (); progressive = request.AllowReadStreamBuffering; Headers = new WebHeaderCollection (); SetMethod (request.Method); if (native == IntPtr.Zero) return; // Get the status code and status text asap, this way we don't have to // ref/unref the native ptr int status_code = NativeMethods.http_response_get_response_status (native); SetStatus ((HttpStatusCode) status_code, (status_code == 200 || status_code == 404) ? NativeMethods.http_response_get_response_status_text (native) : "Requested resource was not found"); GCHandle handle = GCHandle.Alloc (this); NativeMethods.http_response_visit_headers (native, OnHttpHeader, GCHandle.ToIntPtr (handle)); handle.Free (); }
/** * Validates the passed request by reconstructing the original URL and * parameters and generating a signature following the OAuth HMAC-SHA1 * specification and using the passed secret key. * * @param request Servlet request containing required information for * reconstructing the signature such as the request's URL * components and parameters * @param consumerSecret Secret key shared between application owner and * container. Used by containers when issuing signed makeRequests * and by client applications to verify the source of these * requests and the authenticity of its parameters. * @return {@code true} if the signature generated in this function matches * the signature in the passed request, {@code false} otherwise * @throws IOException * @throws URISyntaxException */ public static bool verifyHmacSignature( HttpWebRequest request, String consumerSecret) { String method = request.Method; String requestUrl = getRequestUrl(request); List<OAuth.Parameter> requestParameters = getRequestParameters(request); OAuthMessage message = new OAuthMessage(method, requestUrl, requestParameters); OAuthConsumer consumer = new OAuthConsumer(null, null, consumerSecret, null); OAuthAccessor accessor = new OAuthAccessor(consumer); try { message.validateMessage(accessor, new SimpleOAuthValidator()); } catch (OAuthException e) { return false; } return true; }
public string GET(string url,WebProxy proxy=null) { LastOK = false; string s = string.Empty; req = (HttpWebRequest)WebRequest.Create(url); req.UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1944.0 Safari/537.36"; req.Proxy = (WebProxy)proxy; req.UseDefaultCredentials = false; req.KeepAlive = false; req.Timeout = 3000; try { using (StreamReader sr = new StreamReader(req.GetResponse().GetResponseStream())) { LastOK = true; return sr.ReadToEnd(); } } catch(Exception ex) { LastError = ex.Message; return null; } }
private void BeginRequest(HttpWebRequest request, System.Action<HttpResult> onResult) { //int total = 0; //byte[] buffer = new byte[1000]; request.BeginGetResponse(new AsyncCallback((result) => { var data = request.EndGetResponse(result); HttpResult r = new HttpResult(); try { var stream = new StreamReader(data.GetResponseStream()); r.response = stream.ReadToEnd(); stream.Close(); //TODO:!! /*stream.BeginRead(buffer, 0, 1000, new AsyncCallback((read) => { var r = stream.EndRead(read); if (r == 0) { //TODO: !! } else { //stream.BeginRead } }));*/ } catch (Exception ex) { r.errDescr = ex.Message; } finally { data.Close(); } if (onResult != null) { onResult(r); } }), null); }
/// <summary> /// Creates a request and invokes it /// </summary> /// <returns></returns> /// <exception cref="MwsException">Exceptions from invoking the request</exception> public IMwsReader invoke() { string responseBody; string message; HttpStatusCode statusCode = default(HttpStatusCode); /* Add required request parameters */ AddRequiredParameters(); string queryString = GetParametersAsString(this.parameters); int retries = 0; do { /* Submit the request and read response body */ try { this.request = this.connection.GetHttpClient(this.serviceEndPoint.URI); byte[] requestData = new UTF8Encoding().GetBytes(queryString); this.request.ContentLength = requestData.Length; using (Stream requestStream = this.request.GetRequestStream()) { requestStream.Write(requestData, 0, requestData.Length); } using (HttpWebResponse httpResponse = this.request.GetResponse() as HttpWebResponse) { statusCode = httpResponse.StatusCode; message = httpResponse.StatusDescription; this.ResponseHeaderMetadata = GetResponseHeaderMetadata(httpResponse); StreamReader reader = new StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8); responseBody = reader.ReadToEnd(); } if (statusCode == HttpStatusCode.OK) { return(new MwsXmlReader(responseBody)); } MwsException e = new MwsException((int)statusCode, message, null, null, responseBody, this.ResponseHeaderMetadata); if (statusCode == HttpStatusCode.InternalServerError) { if (PauseIfRetryNeeded(retries++)) { continue; } } throw e; } /* Web exception is thrown on unsuccessful responses */ catch (WebException we) { using (HttpWebResponse httpErrorResponse = (HttpWebResponse)we.Response as HttpWebResponse) { if (httpErrorResponse == null) { throw new MwsException(we); } statusCode = httpErrorResponse.StatusCode; using (StreamReader reader = new StreamReader(httpErrorResponse.GetResponseStream(), Encoding.UTF8)) { responseBody = reader.ReadToEnd(); } } //retry logic if (PauseIfRetryNeeded(retries++)) { continue; } throw new MwsException((int)statusCode, null, null, null, responseBody, null); } /* Catch other exceptions, attempt to convert to formatted exception, * else rethrow wrapped exception */ catch (Exception e) { throw new MwsException(e); } } while (true); }
/// <summary> /// Http方式下载文件 /// </summary> /// <param name="url">http地址</param> /// <param name="localfile">本地文件</param> /// <returns></returns> public bool Download(string url, string localfile) { bool flag = false; long startPosition = 0; // 上次下载的文件起始位置 FileStream writeStream; // 写入本地文件流对象 long remoteFileLength = GetHttpLength(url);// 取得远程文件长度 //System.Console.WriteLine("remoteFileLength=" + remoteFileLength); if (remoteFileLength == 745) { System.Console.WriteLine("远程文件不存在."); return false; } // 判断要下载的文件夹是否存在 if (File.Exists(localfile)) { writeStream = File.OpenWrite(localfile); // 存在则打开要下载的文件 startPosition = writeStream.Length; // 获取已经下载的长度 if (startPosition >= remoteFileLength) { System.Console.WriteLine("本地文件长度" + startPosition + "已经大于等于远程文件长度" + remoteFileLength); writeStream.Close(); return false; } else { writeStream.Seek(startPosition, SeekOrigin.Current); // 本地文件写入位置定位 } } else { writeStream = new FileStream(localfile, FileMode.Create);// 文件不保存创建一个文件 startPosition = 0; } try { HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(url);// 打开网络连接 if (startPosition > 0) { myRequest.AddRange((int)startPosition);// 设置Range值,与上面的writeStream.Seek用意相同,是为了定义远程文件读取位置 } Stream readStream = myRequest.GetResponse().GetResponseStream();// 向服务器请求,获得服务器的回应数据流 byte[] btArray = new byte[512];// 定义一个字节数据,用来向readStream读取内容和向writeStream写入内容 int contentSize = readStream.Read(btArray, 0, btArray.Length);// 向远程文件读第一次 long currPostion = startPosition; while (contentSize > 0)// 如果读取长度大于零则继续读 { currPostion += contentSize; int percent = (int)(currPostion * 100 / remoteFileLength); System.Console.WriteLine("percent=" + percent + "%"); writeStream.Write(btArray, 0, contentSize);// 写入本地文件 contentSize = readStream.Read(btArray, 0, btArray.Length);// 继续向远程文件读取 } //关闭流 writeStream.Close(); readStream.Close(); flag = true; //返回true下载成功 } catch (Exception) { writeStream.Close(); flag = false; //返回false下载失败 } return flag; }
/// <summary> /// This method will be called when user clicks on get status button /// </summary> /// <param name="sender">object, that caused this event</param> /// <param name="e">Event that invoked this function</param> protected void StatusButton_Click(object sender, EventArgs e) { try { if (string.IsNullOrEmpty(msgIdLabel.Text)) { return; } if (this.ReadAndGetAccessToken() == false) { return; } string mmsId = msgIdLabel.Text; string mmsDeliveryStatus; HttpWebRequest mmsStatusRequestObject = (HttpWebRequest)System.Net.WebRequest.Create(string.Empty + this.endPoint + "/rest/mms/2/messaging/outbox/" + mmsId); mmsStatusRequestObject.Headers.Add("Authorization", "Bearer " + this.accessToken); mmsStatusRequestObject.Method = "GET"; HttpWebResponse mmsStatusResponseObject = (HttpWebResponse)mmsStatusRequestObject.GetResponse(); using (StreamReader mmsStatusResponseStream = new StreamReader(mmsStatusResponseObject.GetResponseStream())) { mmsDeliveryStatus = mmsStatusResponseStream.ReadToEnd(); mmsDeliveryStatus = mmsDeliveryStatus.Replace("-", string.Empty); JavaScriptSerializer deserializeJsonObject = new JavaScriptSerializer(); GetDeliveryStatus status = (GetDeliveryStatus)deserializeJsonObject.Deserialize(mmsDeliveryStatus, typeof(GetDeliveryStatus)); DeliveryInfoList dinfoList = status.DeliveryInfoList; this.DrawPanelForGetStatusResult(null, null, null, true); foreach (DeliveryInfoRaw deliveryInfo in dinfoList.DeliveryInfo) { this.DrawPanelForGetStatusResult(deliveryInfo.Id, deliveryInfo.Address, deliveryInfo.DeliveryStatus, false); } msgIdLabel.Text = string.Empty; mmsStatusResponseStream.Close(); } } catch (WebException we) { string errorResponse = string.Empty; try { using (StreamReader sr2 = new StreamReader(we.Response.GetResponseStream())) { errorResponse = sr2.ReadToEnd(); sr2.Close(); } } catch { errorResponse = "Unable to get response"; } this.DrawPanelForFailure(statusPanel, errorResponse + Environment.NewLine + we.Message); } catch (Exception ex) { this.DrawPanelForFailure(statusPanel, ex.ToString()); } }
public void Abort_BeginGetResponseUsingNoCallbackThenAbort_Success(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); _savedHttpWebRequest.BeginGetResponse(null, null); _savedHttpWebRequest.Abort(); }
public void OnRequest(HttpWebRequest webRequest) { webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; webRequest.Headers.Add("From", "bingbot(at)microsoft.com"); webRequest.UserAgent = "Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)"; }
protected ResponseData RequestPost(string json, string action, NameValueCollection headers = null) { try { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_serverAddress + action); // Set the Method property of the request to POST. request.Method = "POST"; if (headers != null) { request.Headers.Add(headers); } // Create POST data and convert it to a byte array. //WRITE JSON DATA TO VARIABLE D //string postData = "{\"requests\":[{\"C\":\"Gpf_Auth_Service\", \"M\":\"authenticate\", \"fields\":[[\"name\",\"value\"],[\"Id\",\"\"],[\"username\",\"[email protected]\"],[\"password\",\"ab9ce908\"],[\"rememberMe\",\"Y\"],[\"language\",\"en-US\"],[\"roleType\",\"M\"]]}],\"C\":\"Gpf_Rpc_Server\", \"M\":\"run\"}"; string postData = json; byte[] byteArray = Encoding.UTF8.GetBytes(postData); // Set the ContentType property of the WebRequest. request.ContentType = MimeType; //request.Headers.Add("Accept-Encoding", "gzip,deflate"); // Set the ContentLength property of the WebRequest. request.ContentLength = byteArray.Length; // Get the request stream. Stream dataStream = request.GetRequestStream(); // Write the data to the request stream. dataStream.Write(byteArray, 0, byteArray.Length); // Close the Stream object. dataStream.Close(); // Get the response. //request.Timeout = 740 * 1000; if (EDDiscoveryForm.EDDConfig.EDSMLog) { WriteLog("POST " + request.RequestUri, postData); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); var data = getResponseData(response); response.Close(); if (EDDiscoveryForm.EDDConfig.EDSMLog) { //TODO: Log Status Code too WriteLog(data.Body, ""); } return(data); } catch (WebException ex) { using (WebResponse response = ex.Response) { HttpWebResponse httpResponse = (HttpWebResponse)response; var data = getResponseData(httpResponse); System.Diagnostics.Trace.WriteLine(ex.StackTrace); System.Diagnostics.Trace.WriteLine("WebException : " + ex.Message); System.Diagnostics.Trace.WriteLine("Response code : " + httpResponse.StatusCode); System.Diagnostics.Trace.WriteLine("Response body : " + data.Body); System.Diagnostics.Trace.WriteLine(ex.StackTrace); if (EDDiscoveryForm.EDDConfig.EDSMLog) { WriteLog("WebException" + ex.Message, ""); WriteLog($"HTTP Error code: {httpResponse.StatusCode}", ""); WriteLog($"HTTP Error body: {data.Body}", ""); } return(data); } } } catch (Exception ex) { System.Diagnostics.Trace.WriteLine("Exception : " + ex.Message); System.Diagnostics.Trace.WriteLine(ex.StackTrace); if (EDDiscoveryForm.EDDConfig.EDSMLog) { WriteLog("Exception" + ex.Message, ""); } return(new ResponseData(HttpStatusCode.BadRequest)); } }
/// <summary> /// Constructs a web request to clear all messages in the queue. /// </summary> /// <param name="uri">A <see cref="System.Uri"/> specifying the absolute URI to the queue.</param> /// <param name="timeout">An integer specifying the server timeout interval.</param> /// <param name="useVersionHeader">A flag indicating whether to set the x-ms-version HTTP header.</param> /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param> /// <returns>A <see cref="System.Net.HttpWebRequest"/> object.</returns> public static HttpWebRequest ClearMessages(Uri uri, int?timeout, bool useVersionHeader, OperationContext operationContext) { HttpWebRequest request = HttpWebRequestFactory.Delete(uri, null, timeout, useVersionHeader, operationContext); return(request); }
/// <summary> /// Generates a web request to return the user-defined metadata for this queue. /// </summary> /// <param name="uri">A <see cref="System.Uri"/> specifying the absolute URI to the queue.</param> /// <param name="timeout">An integer specifying the server timeout interval.</param> /// <param name="useVersionHeader">A flag indicating whether to set the x-ms-version HTTP header.</param> /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param> /// <returns>A <see cref="System.Net.HttpWebRequest"/> object.</returns> public static HttpWebRequest GetMetadata(Uri uri, int?timeout, bool useVersionHeader, OperationContext operationContext) { HttpWebRequest request = HttpWebRequestFactory.GetMetadata(uri, timeout, null, useVersionHeader, operationContext); return(request); }
/// <summary> /// Adds user-defined metadata to the request as one or more name-value pairs. /// </summary> /// <param name="request">A <see cref="System.Net.HttpWebRequest"/> object.</param> /// <param name="metadata">A <see cref="Dictionary{TKey,TValue}"/> object containing the user-defined metadata.</param> public static void AddMetadata(HttpWebRequest request, IDictionary <string, string> metadata) { HttpWebRequestFactory.AddMetadata(request, metadata); }
/// <summary> /// Adds user-defined metadata to the request as a single name-value pair. /// </summary> /// <param name="request">A <see cref="System.Net.HttpWebRequest"/> object.</param> /// <param name="name">A string containing the metadata name.</param> /// <param name="value">A string containing the metadata value.</param> public static void AddMetadata(HttpWebRequest request, string name, string value) { HttpWebRequestFactory.AddMetadata(request, name, value); }
/// <summary> /// Constructs a web request to set the ACL for a queue. /// </summary> /// <param name="uri">A <see cref="System.Uri"/> specifying the absolute URI to the queue.</param> /// <param name="timeout">An integer specifying the server timeout interval.</param> /// <param name="useVersionHeader">A flag indicating whether to set the x-ms-version HTTP header.</param> /// <param name="operationContext">An <see cref="OperationContext"/> object that represents the context for the current operation.</param> /// <returns>A <see cref="System.Net.HttpWebRequest"/> object.</returns> public static HttpWebRequest SetAcl(Uri uri, int?timeout, bool useVersionHeader, OperationContext operationContext) { HttpWebRequest request = HttpWebRequestFactory.SetAcl(uri, null, timeout, useVersionHeader, operationContext); return(request); }
/// <summary> /// 删除Heard /// </summary> /// <param name="pRequest"></param> public void PTRequest(ref HttpWebRequest pRequest) { pRequest.Headers.Remove("x-requested-with"); }
/** * Constructs and returns a List of OAuth.Parameter objects, one per * parameter in the passed request. * * @param request Servlet request object with methods for retrieving the * full set of parameters passed with the request */ public static List<OAuth.Parameter> getRequestParameters( HttpWebRequest request) { List<OAuth.Parameter> parameters = new List<OAuth.Parameter>(); for (int i = 0; i < request.Headers.Count; i++) { if (request.Headers.GetValues(i) == null) continue; foreach (String value in request.Headers.GetValues(i)) { parameters.Add(new OAuth.Parameter(request.Headers.GetKey(i), value)); } } var q = HttpUtility.ParseQueryString(request.RequestUri.Query); for (int i = 0; i < q.Count; i++) { if (q.GetValues(i) == null) continue; foreach (String value in q.GetValues(i)) { parameters.Add(new OAuth.Parameter(q.GetKey(i), value)); } } return parameters; }
protected ResponseData RequestDelete(string action, NameValueCollection headers = null) { try { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_serverAddress + action); request.Method = "DELETE"; // Set the ContentType property of the WebRequest. request.ContentType = MimeType; request.Headers.Add("Accept-Encoding", "gzip,deflate"); if (headers != null) { request.Headers.Add(headers); } request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; if (EDDiscoveryForm.EDDConfig.EDSMLog) { WriteLog("DELETE " + request.RequestUri, ""); } // Get the response. //request.Timeout = 740 * 1000; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); var data = getResponseData(response); response.Close(); if (EDDiscoveryForm.EDDConfig.EDSMLog) { WriteLog(data.Body, ""); } return(data); } catch (WebException ex) { using (WebResponse response = ex.Response) { HttpWebResponse httpResponse = (HttpWebResponse)response; var data = getResponseData(httpResponse); System.Diagnostics.Trace.WriteLine(ex.StackTrace); System.Diagnostics.Trace.WriteLine("WebException : " + ex.Message); System.Diagnostics.Trace.WriteLine("Response code : " + httpResponse.StatusCode); System.Diagnostics.Trace.WriteLine("Response body : " + data.Body); System.Diagnostics.Trace.WriteLine(ex.StackTrace); if (EDDiscoveryForm.EDDConfig.EDSMLog) { WriteLog("WebException" + ex.Message, ""); WriteLog($"HTTP Error code: {httpResponse.StatusCode}", ""); WriteLog($"HTTP Error body: {data.Body}", ""); } return(data); } } } catch (Exception ex) { System.Diagnostics.Trace.WriteLine("Exception : " + ex.Message); System.Diagnostics.Trace.WriteLine(ex.StackTrace); if (EDDiscoveryForm.EDDConfig.EDSMLog) { WriteLog("Exception" + ex.Message, ""); } return(new ResponseData(HttpStatusCode.BadRequest)); } }
public HttpRsepData Post2ReceiveData(string strUrl, string HttpRequestData) { HttpRsepData RespData = new HttpRsepData(); Encoding encode = System.Text.Encoding.UTF8; //注意提交的编码 这边是需要改变的 这边默认的是Default:系统当前编码 #if false byte[] arrB = encode.GetBytes(HttpRequestData); #else byte[] arrB = Encoding.UTF8.GetBytes(HttpRequestData); #endif CookieContainer cookieContainer = new CookieContainer(); HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(strUrl); myReq.Method = "POST"; myReq.ContentType = "application/x-www-form-urlencoded"; myReq.ContentLength = arrB.Length; myReq.CookieContainer = cookieContainer; try { Stream outStream = myReq.GetRequestStream(); //其他信息: 无法连接到远程服务器 outStream.Write(arrB, 0, arrB.Length); outStream.Close(); } catch (Exception ex) { shijian(); MessageBox.Show("网络错误,请稍后连接!"); } WebResponse myResp = null; try { //接收HTTP做出的响应 myResp = myReq.GetResponse(); } catch (Exception e) { int ii = 0; } if (myResp != null) { RespData.RespStatus = ((HttpWebResponse)myResp).StatusDescription; if (RespData.RespStatus == HttpOK) { RespData.RespStatusCode = 200; Encoding respencode = System.Text.Encoding.UTF8; Stream ReceiveStream = myResp.GetResponseStream(); StreamReader readStream = new StreamReader(ReceiveStream, respencode); RespData.RespData = readStream.ReadToEnd(); Jsontext = RespData.RespData; } else if (RespData.RespStatus == HttpNotFing) { RespData.RespStatusCode = 400; } else { RespData.RespStatusCode = -1; } } else { RespData.RespStatus = "服务器未连接-HttpWebRequest"; RespData.RespStatusCode = -1; } return(RespData); }
/// <param name="date">The current date and time, used to authenticate /// the API request. Typically, you should specify DateTime.UtcNow, /// but if you do not wish to rely on the system-wide clock, you may /// determine the current date/time by some other means.</param> /// <param name="timeout">The request timeout, in milliseconds. /// Specify 0 to use the system-default timeout. Use caution if /// you choose to specify a custom timeout - some API /// calls (particularly in the Auth and Verify APIs) will not /// return a response until an out-of-band authentication process /// has completed. In some cases, this may take as much as a /// small number of minutes.</param> public string ApiCall(string method, string path, Dictionary <string, string> parameters, int timeout, DateTime date, out HttpStatusCode statusCode) { string canon_params = DuoApi.CanonicalizeParams(parameters); string query = ""; if (!method.Equals("POST") && !method.Equals("PUT")) { if (parameters.Count > 0) { query = "?" + canon_params; } } string url = string.Format("{0}://{1}{2}{3}", this.url_scheme, this.host, path, query); string date_string = DuoApi.DateToRFC822(date); string auth = this.Sign(method, path, canon_params, date_string); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = method; request.Accept = "application/json"; request.Headers.Add("Authorization", auth); request.Headers.Add("X-Duo-Date", date_string); request.UserAgent = this.user_agent; // If no proxy, check for and use WinHTTP proxy as autoconfig won't pick this up when run from a service if (!HasProxyServer(request)) { request.Proxy = GetWinhttpProxy(); } if (method.Equals("POST") || method.Equals("PUT")) { byte[] data = Encoding.UTF8.GetBytes(canon_params); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(data, 0, data.Length); } } if (timeout > 0) { request.Timeout = timeout; } // Do the request and process the result. HttpWebResponse response; try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException ex) { response = (HttpWebResponse)ex.Response; if (response == null) { throw; } } StreamReader reader = new StreamReader(response.GetResponseStream()); statusCode = response.StatusCode; return(reader.ReadToEnd()); }
protected ResponseData RequestPatch(string json, string action, NameValueCollection headers = null) { try { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_serverAddress + action); request.Method = "PATCH"; if (headers != null) { request.Headers.Add(headers); } string postData = json; byte[] byteArray = Encoding.UTF8.GetBytes(postData); // Set the ContentType property of the WebRequest. request.ContentType = MimeType; //request.Headers.Add("Accept-Encoding", "gzip,deflate"); // Set the ContentLength property of the WebRequest. request.ContentLength = byteArray.Length; // Get the request stream. Stream dataStream = request.GetRequestStream(); // Write the data to the request stream. dataStream.Write(byteArray, 0, byteArray.Length); // Close the Stream object. dataStream.Close(); // Get the response. //request.Timeout = 740 * 1000; if (EDDiscoveryForm.EDDConfig.EDSMLog) { WriteLog("PATCH " + request.RequestUri, postData); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); var data = getResponseData(response); response.Close(); if (EDDiscoveryForm.EDDConfig.EDSMLog) { WriteLog(data.Body, ""); } return(data); } catch (WebException ex) { using (WebResponse response = ex.Response) { HttpWebResponse httpResponse = (HttpWebResponse)response; var data = getResponseData(httpResponse); System.Diagnostics.Trace.WriteLine(ex.StackTrace); System.Diagnostics.Trace.WriteLine("WebException : " + ex.Message); System.Diagnostics.Trace.WriteLine("Response code : " + httpResponse.StatusCode); System.Diagnostics.Trace.WriteLine("Response body : " + data.Body); System.Diagnostics.Trace.WriteLine(ex.StackTrace); if (EDDiscoveryForm.EDDConfig.EDSMLog) { WriteLog("WebException" + ex.Message, ""); WriteLog($"HTTP Error code: {httpResponse.StatusCode}", ""); WriteLog($"HTTP Error body: {data.Body}", ""); } return(data); } } } catch (Exception ex) { System.Diagnostics.Trace.WriteLine("Exception : " + ex.Message); System.Diagnostics.Trace.WriteLine(ex.StackTrace); if (EDDiscoveryForm.EDDConfig.EDSMLog) { WriteLog("Exception" + ex.Message, ""); } return(new ResponseData(HttpStatusCode.BadRequest)); } }
/// <summary> /// Performs the entire AM2RLauncher update procedure. /// </summary> public static void Main() { log.Info("Running update check..."); // Update section // Clean old files that have been left if (File.Exists(CrossPlatformOperations.CURRENTPATH + "/AM2RLauncher.bak")) { log.Info("AM2RLauncher.bak detected. Removing file."); File.Delete(CrossPlatformOperations.CURRENTPATH + "/AM2RLauncher.bak"); } if (OS.IsWindows && File.Exists(oldConfigPath)) { log.Info(CrossPlatformOperations.LAUNCHERNAME + ".oldCfg detected. Removing file."); File.Delete(oldConfigPath); } if (OS.IsWindows && Directory.Exists(CrossPlatformOperations.CURRENTPATH + "/oldLib")) { log.Info("Old lib folder detected, removing folder."); Directory.Delete(CrossPlatformOperations.CURRENTPATH + "/oldLib", true); } // Clean up old update libs if (OS.IsWindows && Directory.Exists(CrossPlatformOperations.CURRENTPATH + "/lib")) { foreach (FileInfo file in new DirectoryInfo(CrossPlatformOperations.CURRENTPATH + "/lib").GetFiles()) { if (file.Name.EndsWith(".bak")) { file.Delete(); } } // Do the same for each subdir foreach (DirectoryInfo dir in new DirectoryInfo(CrossPlatformOperations.CURRENTPATH + "/lib").GetDirectories()) { foreach (FileInfo file in dir.GetFiles()) { if (file.Name.EndsWith(".bak")) { file.Delete(); } } } } // Check settings if autoUpdateLauncher is set to true bool autoUpdate = Boolean.Parse(CrossPlatformOperations.ReadFromConfig("AutoUpdateLauncher")); if (autoUpdate) { log.Info("AutoUpdate Launcher set to true!"); // This is supposed to fix the updater throwing an exception on windows 7 and earlier(?) // See this for information: https://stackoverflow.com/q/2859790 and https://stackoverflow.com/a/50977774 if (OS.IsWindows) { ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; } HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://github.com/AM2R-Community-Developers/AM2RLauncher/releases/latest"); HttpWebResponse response; try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException) { log.Error("WebException caught! Displaying MessageBox."); MessageBox.Show(Language.Text.NoInternetConnection); return; } Uri realUri = response.ResponseUri; string onlineVersion = realUri.AbsoluteUri.Substring(realUri.AbsoluteUri.LastIndexOf('/') + 1); bool isCurrentVersionOutdated = false; string[] localVersionArray = VERSION.Split('.'); string[] onlineVersionArray = onlineVersion.Split('.'); for (int i = 0; i < localVersionArray.Length; i++) { int onlineNum = Int32.Parse(onlineVersionArray[i]); int localNum = Int32.Parse(localVersionArray[i]); if (onlineNum > localNum) { isCurrentVersionOutdated = true; break; } if (localNum > onlineNum) { break; } } log.Info((isCurrentVersionOutdated ? "Updating" : "Not Updating") + " from " + VERSION + " to " + onlineVersion); // No new update, exiting if (!isCurrentVersionOutdated) { return; } // For mac, we just show a message box that a new version is available, because I don't want to support it yet. // hardcoded string, since also temporarily until it gets supported one day. if (OS.IsMac) { MessageBox.Show("Your current version is outdated! The newest version is " + onlineVersion + "." + "Please recompile AM2RLauncher again or disable auto-updating"); return; } log.Info("Current version (" + VERSION + ") is outdated! Initiating update for version " + onlineVersion + "."); string tmpUpdatePath = CrossPlatformOperations.CURRENTPATH + "/tmpupdate/"; string zipPath = CrossPlatformOperations.CURRENTPATH + "/launcher.zip"; // Clean tmpupdate if (Directory.Exists(tmpUpdatePath)) { Directory.Delete(tmpUpdatePath, true); } if (!Directory.Exists(tmpUpdatePath)) { Directory.CreateDirectory(tmpUpdatePath); } try { using (var client = new WebClient()) { string platformSuffix = ""; if (OS.IsWindows) { platformSuffix = "_win"; } else if (OS.IsLinux) { platformSuffix = "_lin"; } log.Info("Downloading https://github.com/AM2R-Community-Developers/AM2RLauncher/releases/latest/download/AM2RLauncher_" + onlineVersion + platformSuffix + ".zip to " + zipPath + "."); client.DownloadFile("https://github.com/AM2R-Community-Developers/AM2RLauncher/releases/latest/download/AM2RLauncher_" + onlineVersion + platformSuffix + ".zip", zipPath); log.Info("File successfully downloaded."); } } catch (UnauthorizedAccessException) { log.Error("UnauthorizedAccessException caught! Displaying MessageBox."); MessageBox.Show(Language.Text.UnauthorizedAccessMessage); return; } ZipFile.ExtractToDirectory(zipPath, tmpUpdatePath); log.Info("Updates successfully extracted to " + tmpUpdatePath); File.Delete(zipPath); File.Move(updatePath + "/" + CrossPlatformOperations.LAUNCHERNAME, CrossPlatformOperations.CURRENTPATH + "/AM2RLauncher.bak"); if (OS.IsWindows) { File.Move(CrossPlatformOperations.LAUNCHERNAME + ".config", CrossPlatformOperations.LAUNCHERNAME + ".oldCfg"); } foreach (var file in new DirectoryInfo(tmpUpdatePath).GetFiles()) { log.Info("Moving " + file.FullName + " to " + CrossPlatformOperations.CURRENTPATH + "/" + file.Name); File.Copy(file.FullName, updatePath + "/" + file.Name, true); } // For windows, the actual application is in "AM2RLauncher.dll". Which means, we need to update the lib folder as well. if (OS.IsWindows && Directory.Exists(CrossPlatformOperations.CURRENTPATH + "/lib")) { // So, because Windows behavior is dumb... // Rename all files in lib to *.bak foreach (FileInfo file in new DirectoryInfo(CrossPlatformOperations.CURRENTPATH + "/lib").GetFiles()) { file.CopyTo(file.Directory + "/" + file.Name + ".bak"); } // Do the same for each subdir foreach (DirectoryInfo dir in new DirectoryInfo(CrossPlatformOperations.CURRENTPATH + "/lib").GetDirectories()) { foreach (FileInfo file in dir.GetFiles()) { file.CopyTo(file.Directory + "/" + file.Name + ".bak"); } } // Yes, the above calls could be recursive. No, I can't be bothered to make them as such. if (Directory.Exists(tmpUpdatePath + "lib")) { HelperMethods.DirectoryCopy(tmpUpdatePath + "lib", CrossPlatformOperations.CURRENTPATH + "/lib"); } } Directory.Delete(tmpUpdatePath, true); CrossPlatformOperations.CopyOldConfigToNewConfig(); log.Info("Files extracted. Preparing to restart executable..."); if (OS.IsLinux) { System.Diagnostics.Process.Start("chmod", "+x " + updatePath + "./AM2RLauncher.Gtk"); } System.Diagnostics.Process.Start(updatePath + "/" + CrossPlatformOperations.LAUNCHERNAME); Environment.Exit(0); } else { log.Info("AutoUpdate Launcher set to false. Exiting update check."); } }
public static void Demo3(string url, string indata) { string outdata = ""; CookieContainer myCookieContainer = new CookieContainer(); //新建一个CookieContainer来存放Cookie集合 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); //新建一个HttpWebRequest request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = indata.Length; request.Method = "POST"; request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Q312461; .NET CLR 1.0.3705)"; request.CookieContainer = myCookieContainer; //设置HttpWebRequest的CookieContainer为刚才建立的那个myCookieContainer Stream myRequestStream = request.GetRequestStream(); StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312")); myStreamWriter.Write(indata, 0, indata.Length); //把数据写入HttpWebRequest的Request流 myStreamWriter.Close(); myRequestStream.Close(); //关闭打开对象 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //新建一个HttpWebResponse response.Cookies = myCookieContainer.GetCookies(request.RequestUri); //获取一个包含url的Cookie集合的CookieCollection Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("gb2312")); outdata = myStreamReader.ReadToEnd(); //把数据从HttpWebResponse的Response流中读出 myStreamReader.Close(); myResponseStream.Close(); Console.WriteLine(outdata); //显示"登录" //拿到了Cookie,再进行请求就能直接读取到登录后的内容了 request = (HttpWebRequest)WebRequest.Create(url); request.CookieContainer = myCookieContainer;//* //刚才那个CookieContainer已经存有了Cookie,把它附加到HttpWebRequest中则能直接通过验证 response = (HttpWebResponse)request.GetResponse(); response.Cookies = myCookieContainer.GetCookies(request.RequestUri); myResponseStream = response.GetResponseStream(); myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("gb2312")); outdata = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); Console.WriteLine(outdata); //再次显示"登录" //如果把*行注释调,就显示"没有登录" request = (HttpWebRequest)WebRequest.Create(url); request.CookieContainer = myCookieContainer;//*解析到的CookieContainer response = (HttpWebResponse)request.GetResponse(); response.Cookies = myCookieContainer.GetCookies(request.RequestUri); myResponseStream = response.GetResponseStream(); myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("gb2312")); outdata = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); }
public virtual void SetAuth(HttpWebRequest request, Stream body) { }
IEnumerator PostNewTarget() { string requestPath = "/targets"; string serviceURI = url + requestPath; string httpAction = "POST"; string contentType = "application/json"; string date = string.Format("{0:r}", DateTime.Now.ToUniversalTime()); Debug.Log(date); // if your texture2d has RGb24 type, don't need to redraw new texture2d Texture2D tex = new Texture2D(texture.width, texture.height, TextureFormat.RGB24, false); tex.SetPixels(texture.GetPixels()); tex.Apply(); byte[] image = tex.EncodeToPNG(); string metadataStr = "Vuforia metadata";//May use for key,name...in game byte[] metadata = System.Text.ASCIIEncoding.ASCII.GetBytes(metadataStr); PostNewTrackableRequest model = new PostNewTrackableRequest(); model.name = targetName; model.width = 64.0f; // don't need same as width of texture model.image = System.Convert.ToBase64String(image); model.application_metadata = System.Convert.ToBase64String(metadata); //string requestBody = JsonWriter.Serialize(model); string requestBody = JsonUtility.ToJson(model); WWWForm form = new WWWForm(); var headers = form.headers; byte[] rawData = form.data; headers["host"] = url; headers["date"] = date; headers["Content-Type"] = contentType; HttpWebRequest httpWReq = (HttpWebRequest)HttpWebRequest.Create(serviceURI); MD5 md5 = MD5.Create(); var contentMD5bytes = md5.ComputeHash(System.Text.Encoding.ASCII.GetBytes(requestBody)); System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < contentMD5bytes.Length; i++) { sb.Append(contentMD5bytes[i].ToString("x2")); } string contentMD5 = sb.ToString(); string stringToSign = string.Format("{0}\n{1}\n{2}\n{3}\n{4}", httpAction, contentMD5, contentType, date, requestPath); HMACSHA1 sha1 = new HMACSHA1(System.Text.Encoding.ASCII.GetBytes(secret_key)); byte[] sha1Bytes = System.Text.Encoding.ASCII.GetBytes(stringToSign); MemoryStream stream = new MemoryStream(sha1Bytes); byte[] sha1Hash = sha1.ComputeHash(stream); string signature = System.Convert.ToBase64String(sha1Hash); headers["Authorization"] = string.Format("VWS {0}:{1}", access_key, signature); Debug.Log("<color=green>Signature: " + signature + "</color>"); WWW request = new WWW(serviceURI, System.Text.Encoding.UTF8.GetBytes(JsonUtility.ToJson(model)), headers); yield return(request); //AssetDatabase.Refresh(); if (request.error != null) { Debug.Log("request error: " + request.error); } else { Debug.Log("request success"); Debug.Log("returned data" + request.text); } //AssetDatabase.Refresh(); }
public bool doPost(string sUrl, string data, string referer, int timeout) { bool _dosuccess = false; HttpWebRequest _urlConn = null; try { _urlConn = (HttpWebRequest)WebRequest.Create(sUrl); //連線最大等待時間 _urlConn.Timeout = timeout; _urlConn.Method = "POST"; //_urlConn.ServicePoint.Expect100Continue = false; _urlConn.Headers.Set("Content-Encoding", "UTF-8"); _urlConn.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate"); _urlConn.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; //設定referer if (referer != null) { _urlConn.Referer = referer; } _urlConn.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; //自動從導 // _urlConn.AllowAutoRedirect = true; if (data == null) { data = ""; } //把要傳送的資料變成binary byte[] _bytes = Encoding.UTF8.GetBytes(data); _urlConn.ContentLength = _bytes.Length; //設定Cookie,Session _urlConn.CookieContainer = s_cookie; //送出post資料 if (data.Length > 0) { Stream _oStreamOut = _urlConn.GetRequestStream(); _oStreamOut.Write(_bytes, 0, _bytes.Length); _oStreamOut.Close(); } //取回回傳內容 m_buff = (new StreamReader(_urlConn.GetResponse().GetResponseStream())).ReadToEnd(); _dosuccess = true; } catch (WebException _e) { } catch (Exception _e) { } finally { try { if (_urlConn != null) { _urlConn.GetResponse().Close(); _urlConn.GetRequestStream().Close(); } } catch { } } return(_dosuccess); }
public void Abort_CreateRequestThenAbort_Success(Uri remoteServer) { _savedHttpWebRequest = HttpWebRequest.CreateHttp(remoteServer); _savedHttpWebRequest.Abort(); }
/// <summary> /// Sends MMS message by invoking Send MMS api /// </summary> private void SendMMS() { Stream postStream = null; FileStream fileStream = null; BinaryReader binaryReader = null; try { string mmsFilePath = Request.MapPath(this.couponPath); string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x"); HttpWebRequest mmsRequestObject = (HttpWebRequest)WebRequest.Create(string.Empty + this.endPoint + "/rest/mms/2/messaging/outbox"); mmsRequestObject.Headers.Add("Authorization", "Bearer " + this.accessToken); mmsRequestObject.ContentType = "multipart/form-data; type=\"application/x-www-form-urlencoded\"; start=\"<startpart>\"; boundary=\"" + boundary + "\"\r\n"; mmsRequestObject.Method = "POST"; mmsRequestObject.KeepAlive = true; UTF8Encoding encoding = new UTF8Encoding(); byte[] postBytes = encoding.GetBytes(string.Empty); string sendMMSData = this.phoneNumbersParameter + "&Subject=" + Server.UrlEncode(subjectLabel.Text.ToString()); string data = string.Empty; fileStream = new FileStream(mmsFilePath + this.couponFileName, FileMode.Open, FileAccess.Read); binaryReader = new BinaryReader(fileStream); byte[] image = binaryReader.ReadBytes((int)fileStream.Length); data += "--" + boundary + "\r\n"; data += "Content-Type:application/x-www-form-urlencoded;charset=UTF-8\r\nContent-Transfer-Encoding:8bit\r\nContent-ID:<startpart>\r\n\r\n" + sendMMSData + "\r\n"; data += "--" + boundary + "\r\n"; data += "Content-Disposition:attachment;name=\"" + "coupon.jpg" + "\"\r\n"; data += "Content-Type:image/gif\r\n"; data += "Content-ID:<" + "coupon.jpg" + ">\r\n"; data += "Content-Transfer-Encoding:binary\r\n\r\n"; byte[] firstPart = encoding.GetBytes(data); int newSize = firstPart.Length + image.Length; var memoryStream = new MemoryStream(new byte[newSize], 0, newSize, true, true); memoryStream.Write(firstPart, 0, firstPart.Length); memoryStream.Write(image, 0, image.Length); byte[] secondpart = memoryStream.GetBuffer(); byte[] thirdpart = encoding.GetBytes("\r\n--" + boundary + "--\r\n"); newSize = secondpart.Length + thirdpart.Length; var memoryStream2 = new MemoryStream(new byte[newSize], 0, newSize, true, true); memoryStream2.Write(secondpart, 0, secondpart.Length); memoryStream2.Write(thirdpart, 0, thirdpart.Length); postBytes = memoryStream2.GetBuffer(); mmsRequestObject.ContentLength = postBytes.Length; postStream = mmsRequestObject.GetRequestStream(); postStream.Write(postBytes, 0, postBytes.Length); postStream.Close(); WebResponse mmsResponseObject = mmsRequestObject.GetResponse(); using (StreamReader streamReader = new StreamReader(mmsResponseObject.GetResponseStream())) { string mmsResponseData = streamReader.ReadToEnd(); JavaScriptSerializer deserializeJsonObject = new JavaScriptSerializer(); MmsResponseId deserializedJsonObj = (MmsResponseId)deserializeJsonObject.Deserialize(mmsResponseData, typeof(MmsResponseId)); msgIdLabel.Text = deserializedJsonObj.Id; this.DrawPanelForSuccess(sendMMSPanel, deserializedJsonObj.Id); streamReader.Close(); } /*if (this.invalidPhoneNumbers.Count > 0) * { * this.DrawPanelForFailedNumbers(sendMMSPanel); * }*/ mmsRequestObject = null; } catch (WebException we) { string errorResponse = string.Empty; try { using (StreamReader sr2 = new StreamReader(we.Response.GetResponseStream())) { errorResponse = sr2.ReadToEnd(); sr2.Close(); } } catch { errorResponse = "Unable to get response"; } this.DrawPanelForFailure(sendMMSPanel, errorResponse + Environment.NewLine + we.Message); } catch (Exception ex) { this.DrawPanelForFailure(sendMMSPanel, ex.ToString()); } finally { if (null != binaryReader) { binaryReader.Close(); } if (null != fileStream) { fileStream.Close(); } if (null != postStream) { postStream.Close(); } } }
public void Put(string remotename, System.IO.Stream stream) { HttpWebRequest req = CreateRequest("/" + remotename, ""); req.Method = "PUT"; req.ContentType = "application/octet-stream"; try { req.ContentLength = stream.Length; } catch { } //If we can pre-calculate the MD5 hash before transmission, do so /*if (stream.CanSeek) * { * System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create(); * req.Headers["ETag"] = Core.Utility.ByteArrayAsHexString(md5.ComputeHash(stream)).ToLower(); * stream.Seek(0, System.IO.SeekOrigin.Begin); * * using (System.IO.Stream s = req.GetRequestStream()) * Core.Utility.CopyStream(stream, s); * * //Reset the timeout to the default value of 100 seconds to * // avoid blocking the GetResponse() call * req.Timeout = 100000; * * //The server handles the eTag verification for us, and gives an error if the hash was a mismatch * using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse()) * if ((int)resp.StatusCode >= 300) * throw new WebException(Strings.CloudFiles.FileUploadError, null, WebExceptionStatus.ProtocolError, resp); * * } * else //Otherwise use a client-side calculation */ //TODO: We cannot use the local MD5 calculation, because that could involve a throttled read, // and may invoke various events { string fileHash = null; long streamLen = -1; try { streamLen = stream.Length; } catch {} Utility.AsyncHttpRequest areq = new Utility.AsyncHttpRequest(req); using (System.IO.Stream s = areq.GetRequestStream(streamLen)) using (var mds = new Utility.MD5CalculatingStream(s)) { Utility.Utility.CopyStream(stream, mds, true, m_copybuffer); fileHash = mds.GetFinalHashString(); } string md5Hash = null; //We need to verify the eTag locally try { using (HttpWebResponse resp = (HttpWebResponse)areq.GetResponse()) if ((int)resp.StatusCode >= 300) { throw new WebException(Strings.CloudFiles.FileUploadError, null, WebExceptionStatus.ProtocolError, resp); } else { md5Hash = resp.Headers["ETag"]; } } catch (WebException wex) { //Catch 404 and turn it into a FolderNotFound error if (wex.Response is HttpWebResponse && ((HttpWebResponse)wex.Response).StatusCode == HttpStatusCode.NotFound) { throw new FolderMissingException(wex); } //Other error, just re-throw throw; } if (md5Hash == null || md5Hash.ToLower() != fileHash.ToLower()) { //Remove the broken file try { Delete(remotename); } catch { } throw new Exception(Strings.CloudFiles.ETagVerificationError); } } }
public HttpStatusCode GetResponse(ref string pResponsetext, string pUrl, string pMethod, string pData, string pReferer, int pTime = 10000, string pEncoding = "UTF-8", bool pIsPTHander = true) { Set_Cookies(pUrl); try { DeleteUrlCacheEntry(pUrl); HttpWebRequest pRequest = (HttpWebRequest)WebRequest.Create(pUrl); pRequest.KeepAlive = true; pRequest.Method = pMethod.ToUpper(); pRequest.AllowAutoRedirect = true; pRequest.CookieContainer = CookieContainers; pRequest.Referer = pReferer; pRequest.UserAgent = IE8; pRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; pRequest.Timeout = pTime; pRequest.ReadWriteTimeout = pTime; pRequest.CachePolicy = rcp; pRequest.Headers.Add("x-requested-with", "XMLHttpRequest"); //ProtocolVersion //KeepAlive //Allowautoredirect pRequest.ProtocolVersion = HttpVersion.Version10; pRequest.KeepAlive = false; if (pIsPTHander) { PTRequest(ref pRequest); } Encoding encoding = Encoding.GetEncoding(pEncoding); if (pMethod.ToUpper() != "GET" && pData != null) { byte[] bytes = encoding.GetBytes(pData); pRequest.ContentLength = (long)bytes.Length; pRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; Stream requestStream = pRequest.GetRequestStream(); requestStream.Write(bytes, 0, bytes.Length); requestStream.Close(); } HttpWebResponse httpWebResponse = (HttpWebResponse)pRequest.GetResponse(); StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), encoding); pResponsetext = streamReader.ReadToEnd(); pRequest.Abort(); httpWebResponse.Close(); return(httpWebResponse.StatusCode); } catch (WebException ex) { try { HttpWebResponse response = (HttpWebResponse)ex.Response; if (response.StatusCode == HttpStatusCode.BadRequest) { using (Stream data = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(data)) { string text = reader.ReadToEnd(); pResponsetext = text; Console.WriteLine(text); } } } } catch { return(HttpStatusCode.ExpectationFailed); } return(HttpStatusCode.ExpectationFailed); } }
/// <summary> /// Insert soap envelope into web request /// </summary> /// <returns></returns> private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest) { using (Stream stream = webRequest.GetRequestStream()) { soapEnvelopeXml.Save(stream); } }
/// <summary> /// POST提交 模拟xp IE7.0 /// </summary> /// <param name="uri">访问url</param> /// <param name="refererUri">来源url</param> /// <param name="postData">提交的数据</param> /// <param name="encodingName">编码名称 例如:gb2312</param> /// <param name="webproxy">代理</param> /// <returns></returns> public string Post(string uri, string refererUri, string postData, string encodingName, WebProxy webproxy) { string html = string.Empty; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.Accept = "*/*"; request.Headers.Add("Accept-Language", "zh-cn"); request.ContentType = "application/x-www-form-urlencoded"; request.Headers.Add("UA-CPU", "x86"); request.Headers.Add("Accept-Encoding", "gzip, deflate"); request.UserAgent = @"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 1.1.4322; .NET CLR 3.0.04506.30)"; request.Headers.Add("Cache-Control", "no-cache"); request.CookieContainer = cookieContainer; request.Method = "POST"; if (!string.IsNullOrEmpty(refererUri)) { request.Referer = refererUri; } if (null != webproxy) { request.Proxy = webproxy; if (null != webproxy.Credentials) { request.UseDefaultCredentials = true; } } Encoding encode = Encoding.GetEncoding(encodingName); byte[] bytesSend = encode.GetBytes(postData); request.ContentLength = bytesSend.Length; StringBuilder cookieTextSend = new StringBuilder(); if (cookieContainer != null) { CookieCollection cc = cookieContainer.GetCookies(request.RequestUri); foreach (System.Net.Cookie cokie in cc) { cookieTextSend.Append(cokie + ";"); } } if (cookieTextSend.Length > 0) { long time; time = DateTime.UtcNow.Ticks - (new DateTime(1970, 1, 1)).Ticks; time = (long)(time / 10000); request.Headers.Add("Cookie", string.Concat("cookLastGetMsgTime=", time.ToString(), "; ", cookieTextSend.ToString())); } using (Stream streamSend = request.GetRequestStream()) { streamSend.Write(bytesSend, 0, bytesSend.Length); } using (HttpWebResponse reponse = (HttpWebResponse)request.GetResponse()) { using (Stream streamRespone = reponse.GetResponseStream()) { using (StreamReader streamReaderResponse = new StreamReader(streamRespone, encode)) { html = streamReaderResponse.ReadToEnd(); } } } return(html); }