• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# HttpWebRequest类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中HttpWebRequest的典型用法代码示例。如果您正苦于以下问题:C# HttpWebRequest类的具体用法?C# HttpWebRequest怎么用?C# HttpWebRequest使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



HttpWebRequest类属于命名空间,在下文中一共展示了HttpWebRequest类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: AddRequestXml

    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();
        }
    }
开发者ID:Blogsa,项目名称:blogsa,代码行数:26,代码来源:SendPings.cs


示例2: set_option

            private void set_option(string rel)
            {
                string url = "http://" + URI + "/web/cgi-bin/hi3510/param.cgi?"+rel+"&usr=" + Login + "&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");
            }
开发者ID:rastabaddon,项目名称:QCCTV,代码行数:28,代码来源:JPGDriver.cs


示例3: Request

    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;
        }
    }
开发者ID:Arrem,项目名称:MCForge-MCLawl,代码行数:31,代码来源:HTTPGet.cs


示例4: State

	public State (int id, HttpWebRequest req)
	{
		this.id = id;
		request = req;
		handle = new ManualResetEvent (false);
		handleList.Add (handle);
	}
开发者ID:Jakosa,项目名称:MonoLibraries,代码行数:7,代码来源:tlssave.cs


示例5: OnSendingHeaders

    // 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 {
            }

        }
开发者ID:nlh774,项目名称:DotNetReferenceSource,代码行数:41,代码来源:_CookieModule.cs


示例6: OnReceivedHeaders

        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 {
            }

        }
开发者ID:ArildF,项目名称:masters,代码行数:59,代码来源:_cookiemodule.cs


示例7: InitializeRequest

 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;
 }
开发者ID:Curtisspope,项目名称:MDM_API_AW,代码行数:8,代码来源:DataRetrieval.cs


示例8: AssertRequestDefaults

 /// <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);
 }
开发者ID:pokitdok,项目名称:pokitdok-csharp,代码行数:14,代码来源:PlatformClientTest.cs


示例9: getResponse

            protected HttpWebResponse getResponse(HttpWebRequest request)
            {
                // execute the request

                    HttpWebResponse response = (HttpWebResponse)
                        request.GetResponse();

                    return response;
            }
开发者ID:niranjan-nagaraju,项目名称:SMART-Downloader,代码行数:9,代码来源:BasicDownloader.cs


示例10: InitGCMClient

    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);
    }
开发者ID:asaki0510,项目名称:AlarmRuleSet,代码行数:11,代码来源:GCMSender.cs


示例11: GetReadStreamResult

 /// <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;
 }
开发者ID:nlh774,项目名称:DotNetReferenceSource,代码行数:20,代码来源:GetReadStreamResult.cs


示例12: createDataStream

 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;
 }
开发者ID:Nersle,项目名称:Unity,代码行数:13,代码来源:Postman.cs


示例13: AddProxyInfoToRequest

    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;
    }
开发者ID:blat001,项目名称:Achievement-Sherpa,代码行数:14,代码来源:DownloadHelper.cs


示例14: HttpWebRequestCore

		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;
			}
		}
开发者ID:dfr0,项目名称:moon,代码行数:16,代码来源:HttpWebRequestCore.cs


示例15: GetResponse

    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();
    }
开发者ID:KPratap,项目名称:PropSolutions,代码行数:43,代码来源:Testpage.aspx.cs


示例16: getRequestUrl

  /**
   * 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();
  }
开发者ID:s7loves,项目名称:pesta,代码行数:27,代码来源:OpenSocialRequestValidator.cs


示例17: getResponce

 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);
     }
 }
开发者ID:fazlayrabbi,项目名称:Music-Portfolio,代码行数:20,代码来源:OAuthHelper.cs


示例18: FillRequestWithContent

 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);
             }
         }
     }
 }
开发者ID:rgg1992,项目名称:Test,代码行数:20,代码来源:AbbyyReader.cs


示例19: BrowserHttpWebResponse

		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 ();
		}
开发者ID:shana,项目名称:moon,代码行数:22,代码来源:BrowserHttpWebResponse.cs


示例20: verifyHmacSignature

  /**
   * 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;
  }
开发者ID:s7loves,项目名称:pesta,代码行数:40,代码来源:OpenSocialRequestValidator.cs



注:本文中的HttpWebRequest类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# HttpsTransportBindingElement类代码示例发布时间:2022-05-24
下一篇:
C# HttpVerbs类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap