【问题标题】:Remote HTTP Post with C# [duplicate]使用 C# 进行远程 HTTP 发布 [重复]
【发布时间】:2009-02-13 19:33:12
【问题描述】:

如何在 C# 中执行远程 HTTP 发布(请求)?

【问题讨论】:

    标签: c# webrequest


    【解决方案1】:

    这是我曾经编写的一个小应用程序的代码,用于将带有值的表单发布到 URL。它应该非常健壮。

    _formValues 是一个 Dictionary 包含要发布的变量及其值。

    
    // encode form data
    StringBuilder postString = new StringBuilder();
    bool first=true;
    foreach (KeyValuePair pair in _formValues)
    {
        if(first)
            first=false;
        else
            postString.Append("&");
        postString.AppendFormat("{0}={1}", pair.Key, System.Web.HttpUtility.UrlEncode(pair.Value));
    }
    ASCIIEncoding ascii = new ASCIIEncoding();
    byte[] postBytes = ascii.GetBytes(postString.ToString());
    
    // set up request object
    HttpWebRequest request;
    try
    {
        request = WebRequest.Create(url) as HttpWebRequest;
    }
    catch (UriFormatException)
    {
        request = null;
    }
    if (request == null)
        throw new ApplicationException("Invalid URL: " + url);
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = postBytes.Length;
    
    // add post data to request
    Stream postStream = request.GetRequestStream();
    postStream.Write(postBytes, 0, postBytes.Length);
    postStream.Close();
    
    HttpWebResponse response = request.GetResponse() as HttpWebResponse;
    
    

    【讨论】:

    • 谢谢,关于如何构建 POST 数据的详细信息真的很有帮助!
    • request.GetResponse 必须后跟方括号:request.GetResponse(),无论如何感谢您准备使用的代码 :)
    【解决方案2】:

    您可以使用 WCF 或创建 WebRequest

    var httpRequest = (HttpWebRequest)WebRequest.Create("http://localhost/service.svc");
    var httpRequest.Method = "POST";
    
    using (var outputStream = httpRequest.GetRequestStream())
    {
        // some complicated logic to create the message
    }
    
    var response = httpRequest.GetResponse();
    using (var stream = response.GetResponseStream())
    {
        // some complicated logic to handle the response message.
    }
    

    【讨论】:

      【解决方案3】:

      我用this很简单的类:

       public class   RemotePost{
           private  System.Collections.Specialized.NameValueCollection Inputs 
           = new  System.Collections.Specialized.NameValueCollection() ;
      
          public string  Url  =  "" ;
          public string  Method  =  "post" ;
          public string  FormName  =  "form1" ;
      
          public void  Add( string  name, string value ){
              Inputs.Add(name, value ) ;
           }
      
           public void  Post(){
              System.Web.HttpContext.Current.Response.Clear() ;
      
               System.Web.HttpContext.Current.Response.Write( "<html><head>" ) ;
      
               System.Web.HttpContext.Current.Response.Write( string .Format( "</head><body onload=\"document.{0}.submit()\">" ,FormName)) ;
      
               System.Web.HttpContext.Current.Response.Write( string .Format( "<form name=\"{0}\" method=\"{1}\" action=\"{2}\" >" ,
      
              FormName,Method,Url)) ;
                  for ( int  i = 0 ; i< Inputs.Keys.Count ; i++){
                  System.Web.HttpContext.Current.Response.Write( string .Format( "<input name=\"{0}\" type=\"hidden\" value=\"{1}\">" ,Inputs.Keys[i],Inputs[Inputs.Keys[i]])) ;
               }
              System.Web.HttpContext.Current.Response.Write( "</form>" ) ;
               System.Web.HttpContext.Current.Response.Write( "</body></html>" ) ;
               System.Web.HttpContext.Current.Response.End() ;
           }
      } 
      

      你就这样使用它:

      RemotePost myremotepost   =  new   RemotePost()  ;
      myremotepost.Url  =  "http://www.jigar.net/demo/HttpRequestDemoServer.aspx" ;
      myremotepost.Add( "field1" , "Huckleberry" ) ;
      myremotepost.Add( "field2" , "Finn" ) ;
      myremotepost.Post() ; 
      

      非常干净,易于使用,并封装了所有的渣土。我更喜欢这个而不是直接使用 HttpWebRequest 等等。

      【讨论】:

      • 为什么这会被否决?
      • 如果我没看错的话,它实际上并没有发布表单,而是使用可以发布的表单来响应。
      • 我投了反对票,因为它只在网页响应的上下文中起作用,即使在这种情况下,它也会杀死您在该页面中可能想做的任何其他事情。此外,它只允许发布并忘记帖子,并且是一种复杂的方式。
      【解决方案4】:

      还有System.Net.WebClient

      【讨论】:

        【解决方案5】:

        使用WebRequest.Create() 并设置Method 属性。

        【讨论】:

          【解决方案6】:

          我使用以下代码通过 httpwebrequest 类调用 web 服务:

          internal static string CallWebServiceDetail(string url, string soapbody, 
          int timeout) {
              return CallWebServiceDetail(url, soapbody, null, null, null, null, 
          null, timeout);
          }
          internal static string CallWebServiceDetail(string url, string soapbody, 
          string proxy, string contenttype, string method, string action, 
          string accept, int timeoutMilisecs) {
              var req = (HttpWebRequest) WebRequest.Create(url);
              if (action != null) {
                  req.Headers.Add("SOAPAction", action);
              }
              req.ContentType = contenttype ?? "text/xml;charset=\"utf-8\"";
              req.Accept = accept ?? "text/xml";
              req.Method = method ?? "POST";
              req.Timeout = timeoutMilisecs;
              if (proxy != null) {
                  req.Proxy = new WebProxy(proxy, true);
              }
          
              using(var stm = req.GetRequestStream()) {
                  XmlDocument doc = new XmlDocument();
                  doc.LoadXml(soapbody);
                  doc.Save(stm);
              }
              using(var resp = req.GetResponse()) {
                  using(var responseStream = resp.GetResponseStream()) {
                      using(var reader = new StreamReader(responseStream)) {
                          return reader.ReadToEnd();
                      }
                  }
              }
          }
          

          这可以很容易地用来调用网络服务

          public void TestWebCall() {
              const string url = 
          "http://www.ecubicle.net/whois_service.asmx/HelloWorld";
              const string soap = 
          @"<soap:Envelope xmlns:soap='about:envelope'>
              <soap:Body><HelloWorld /></soap:Body>
          </soap:Envelope>";
              string responseDoc = CallWebServiceDetail(url, soap, 1000);
              XmlDocument doc = new XmlDocument();
              doc.LoadXml(responseDoc);
              string response = doc.DocumentElement.InnerText;
          }
          

          【讨论】:

            【解决方案7】:
            HttpWebRequest HttpWReq = 
            (HttpWebRequest)WebRequest.Create("http://www.google.com");
            
            HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
            Console.WriteLine(HttpWResp.StatusCode);
            HttpWResp.Close();
            

            如果请求成功,应该打印“OK”(200)

            【讨论】:

            • 由于 OP 正在执行 POST,因此您还应该提及请求流方面。
            【解决方案8】:

            从 C#、Java 或 PHP 等高级语言开始的问题是,人们可能永远不知道地下在现实中是多么简单。所以这里有一个简短的介绍:

            http://reboltutorial.com/blog/raw-http-request/

            【讨论】:

              猜你喜欢
              • 2014-10-24
              • 1970-01-01
              • 2017-07-17
              • 1970-01-01
              • 1970-01-01
              • 2010-12-27
              • 2011-11-01
              • 2018-03-19
              • 2021-10-02
              相关资源
              最近更新 更多