简体   繁体   English

.NET:使用数据和读取响应发送POST的最简单方法

[英].NET: Simplest way to send POST with data and read response

To my surprise, I can't do anything nearly as simple as this, from what I can tell, in the .NET BCL: 令我惊讶的是,从.NET BCL中我可以看出,我无法做到这么简单。

byte[] response = Http.Post
(
    url: "http://dork.com/service",
    contentType: "application/x-www-form-urlencoded",
    contentLength: 32,
    content: "home=Cosby&favorite+flavor=flies"
);

This hypothetical code above makes an HTTP POST, with data, and returns the response from a Post method on a static class Http . 上面的假设代码使用数据进行HTTP POST,并在静态类Http上返回Post方法的响应。

Since we're left without something this easy, what's the next best solution? 既然我们没有这么容易,那么下一个最佳解决方案是什么?

How do I send an HTTP POST with data AND get the response's content? 如何发送带有数据的HTTP POST并获取响应的内容?

   using (WebClient client = new WebClient())
   {

       byte[] response =
       client.UploadValues("http://dork.com/service", new NameValueCollection()
       {
           { "home", "Cosby" },
           { "favorite+flavor", "flies" }
       });

       string result = System.Text.Encoding.UTF8.GetString(response);
   }

You will need these includes: 您将需要这些包括:

using System;
using System.Collections.Specialized;
using System.Net;

If you're insistent on using a static method/class: 如果您坚持使用静态方法/类:

public static class Http
{
    public static byte[] Post(string uri, NameValueCollection pairs)
    {
        byte[] response = null;
        using (WebClient client = new WebClient())
        {
            response = client.UploadValues(uri, pairs);
        }
        return response;
    }
}

Then simply: 那简单地说:

var response = Http.Post("http://dork.com/service", new NameValueCollection() {
    { "home", "Cosby" },
    { "favorite+flavor", "flies" }
});

Using HttpClient: as far as Windows 8 app development concerns, I came across this. 使用HttpClient:就Windows 8应用程序开发问题而言,我遇到了这个问题。

var client = new HttpClient();

var pairs = new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("pqpUserName", "admin"),
        new KeyValuePair<string, string>("password", "test@123")
    };

var content = new FormUrlEncodedContent(pairs);

var response = client.PostAsync("youruri", content).Result;

if (response.IsSuccessStatusCode)
{


}

Use WebRequest . 使用WebRequest From Scott Hanselman : 来自Scott Hanselman

public static string HttpPost(string URI, string Parameters) 
{
   System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
   req.Proxy = new System.Net.WebProxy(ProxyString, true);
   //Add these, as we're doing a POST
   req.ContentType = "application/x-www-form-urlencoded";
   req.Method = "POST";
   //We need to count how many bytes we're sending. 
   //Post'ed Faked Forms should be name=value&
   byte [] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
   req.ContentLength = bytes.Length;
   System.IO.Stream os = req.GetRequestStream ();
   os.Write (bytes, 0, bytes.Length); //Push it out there
   os.Close ();
   System.Net.WebResponse resp = req.GetResponse();
   if (resp== null) return null;
   System.IO.StreamReader sr = 
         new System.IO.StreamReader(resp.GetResponseStream());
   return sr.ReadToEnd().Trim();
}
private void PostForm()
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://dork.com/service");
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    string postData ="home=Cosby&favorite+flavor=flies";
    byte[] bytes = Encoding.UTF8.GetBytes(postData);
    request.ContentLength = bytes.Length;

    Stream requestStream = request.GetRequestStream();
    requestStream.Write(bytes, 0, bytes.Length);

    WebResponse response = request.GetResponse();
    Stream stream = response.GetResponseStream();
    StreamReader reader = new StreamReader(stream);

    var result = reader.ReadToEnd();
    stream.Dispose();
    reader.Dispose();
}

Personally, I think the simplest approach to do an http post and get the response is to use the WebClient class. 就个人而言,我认为做一个http帖子并获得响应的最简单方法是使用WebClient类。 This class nicely abstracts the details. 这个类很好地抽象了细节。 There's even a full code example in the MSDN documentation. MSDN文档中甚至还有一个完整的代码示例。

http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.80).aspx http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.80).aspx

In your case, you want the UploadData() method. 在您的情况下,您需要UploadData()方法。 (Again, a code sample is included in the documentation) (同样,代码示例包含在文档中)

http://msdn.microsoft.com/en-us/library/tdbbwh0a(VS.80).aspx http://msdn.microsoft.com/en-us/library/tdbbwh0a(VS.80).aspx

UploadString() will probably work as well, and it abstracts it away one more level. UploadString()可能也会起作用,它会将它抽象出一个级别。

http://msdn.microsoft.com/en-us/library/system.net.webclient.uploadstring(VS.80).aspx http://msdn.microsoft.com/en-us/library/system.net.webclient.uploadstring(VS.80).aspx

I know this is an old thread, but hope it helps some one. 我知道这是一个老线程,但希望它能帮助一些人。

public static void SetRequest(string mXml)
{
    HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.CreateHttp("http://dork.com/service");
    webRequest.Method = "POST";
    webRequest.Headers["SOURCE"] = "WinApp";

    // Decide your encoding here

    //webRequest.ContentType = "application/x-www-form-urlencoded";
    webRequest.ContentType = "text/xml; charset=utf-8";

    // You should setContentLength
    byte[] content = System.Text.Encoding.UTF8.GetBytes(mXml);
    webRequest.ContentLength = content.Length;

    var reqStream = await webRequest.GetRequestStreamAsync();
    reqStream.Write(content, 0, content.Length);

    var res = await httpRequest(webRequest);
}

You can use something like this pseudo code: 你可以使用类似这样的伪代码:

request = System.Net.HttpWebRequest.Create(your url)
request.Method = WebRequestMethods.Http.Post

writer = New System.IO.StreamWriter(request.GetRequestStream())
writer.Write("your data")
writer.Close()

response = request.GetResponse()
reader = New System.IO.StreamReader(response.GetResponseStream())
responseText = reader.ReadToEnd

Given other answers are a few years old, currently here are my thoughts that may be helpful: 鉴于其他答案已有几年历史,目前我的想法可能会有所帮助:

Simplest way 最简单的方法

private async Task<string> PostAsync(Uri uri, HttpContent dataOut)
{
    var client = new HttpClient();
    var response = await client.PostAsync(uri, dataOut);
    return await response.Content.ReadAsStringAsync();
    // For non strings you can use other Content.ReadAs...() method variations
}

A More Practical Example 一个更实际的例子

Often we are dealing with known types and JSON, so you can further extend this idea with any number of implementations, such as: 我们经常处理已知类型和JSON,因此您可以使用任意数量的实现进一步扩展这个想法,例如:

public async Task<T> PostJsonAsync<T>(Uri uri, object dtoOut)
{
    var content = new StringContent(JsonConvert.SerializeObject(dtoOut));
    content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

    var results = await PostAsync(uri, content); // from previous block of code

    return JsonConvert.DeserializeObject<T>(results); // using Newtonsoft.Json
}

An example of how this could be called: 如何调用它的一个例子:

var dataToSendOutToApi = new MyDtoOut();
var uri = new Uri("https://example.com");
var dataFromApi = await PostJsonAsync<MyDtoIn>(uri, dataToSendOutToApi);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将关系数据读入数据集的最简单方法 - Simplest way to read relational data into a DataSet 有没有办法增加在 .NET 核心中的 POST 响应中发送的数据文件的大小? - Is there a way to increase the size of a data file sent in a a POST response in .NET core? 从.NET中的Excel和Word文件读取的最简单方法 - Simplest way to read from Excel and Word Files in .NET Web API获取多部分/表单数据响应的最简单方法 - Web API Simplest way to pickup a multipart/form-data response 从套接字读取数据,发送响应并关闭 - Read data from socket, send response and close 解析Resellerclub HTTP API响应的最简单方法 - simplest way to parse Resellerclub HTTP API Response 使用 Tcpclinet c# 发送对象的最简单方法 - simplest way to send an object with Tcpclinet c# 使用 Ajax [Project .Net] 将发布数据发送到控制器 - Send Post Data to Controller with Ajax [Project .Net] 为C ++实现.NET事件的最简单方法 - Simplest way to implement .NET events for C++ 无法读取流(StreamReader .net),从带有angular(1.5)$ http.post和json的Internet Explorer 10发送数据作为数据 - Stream can not be read (StreamReader .net), send from Internet Explorer 10 with angular (1.5) $http.post and json as data
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM