使用 C# 进行远程 HTTP Post

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/547347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 07:42:33  来源:igfitidea点击:

Remote HTTP Post with C#

c#webrequest

提问by localhost

How do you do a Remote HTTP Post (request) in C#?

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

回答by bendewey

You can use WCF or create a WebRequest

您可以使用 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.
}

回答by BobbyShaftoe

I use thisvery simple class:

我使用这个非常简单的类:

 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() ;
     }
} 

And you use it thusly:

你这样使用它:

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

Very clean, easy to use and encapsulates all the muck. I prefer this to using the HttpWebRequest and so forth directly.

非常干净,易于使用并封装了所有垃圾。我更喜欢直接使用 HttpWebRequest 等。

回答by Eclipse

Use the WebRequest.Create()and set the Methodproperty.

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

回答by John T

HttpWebRequest HttpWReq = 
(HttpWebRequest)WebRequest.Create("http://www.google.com");

HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
Console.WriteLine(HttpWResp.StatusCode);
HttpWResp.Close();

Should print "OK" (200) if the request was successful

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

回答by Joel Coehoorn

Also System.Net.WebClient

System.Net.WebClient

回答by David

This is code from a small app I wrote once to post a form with values to a URL. It should be pretty robust.

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

_formValues is a Dictionary<string,string> containing the variables to post and their values.

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


// 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;

回答by Christian Ernst Rysgaard

Im using the following piece of code for calling webservices using the httpwebrequest class:

我使用以下代码段使用 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();
            }
        }
    }
}

This can be easily used to call a webservice

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

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

回答by Rebol Tutorial

The problem when beginning with high-level language like C#, Java or PHP is that people may have never known how simple the underground is in reality. So here's a short introduction:

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

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

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