.NET:发送带有数据的 POST 并读取响应的最简单方法

问题描述 投票:0回答:9

令我惊讶的是,据我所知,在 .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"
);

上面的假设代码使用数据进行 HTTP POST,并从静态类

Post
上的
Http
方法返回响应。

既然我们没有这么简单的东西,那么下一个最佳解决方案是什么?

如何发送带有数据的 HTTP POST 并获取响应的内容?

c# .net http http-post httpresponse
9个回答
291
投票
   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);
   }

您将需要这些包括:

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

如果您坚持使用静态方法/类:

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

然后简单地说:

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

81
投票

使用 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)
{


}

47
投票

使用WebRequest。来自斯科特汉塞尔曼

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

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

12
投票

就我个人而言,我认为执行 http post 并获取响应的最简单方法是使用 WebClient 类。这个类很好地抽象了细节。 MSDN 文档中甚至还有完整的代码示例。

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

在您的情况下,您需要 UploadData() 方法。 (同样,文档中包含代码示例)

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

UploadString() 可能也能工作,并且它将它抽象了一层。

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


8
投票

鉴于其他答案已有几年历史,目前以下是我的想法可能会有所帮助:

最简单的方法

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
}

更实际的例子

我们通常处理已知类型和 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
}

如何调用它的示例:

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

7
投票

我知道这是一个旧线程,但希望它对某人有所帮助。

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

5
投票

您可以使用类似这样的伪代码:

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

0
投票

这是来自 .net 7 的示例:

请注意,httpClient.PostAsJsonAsync 是一个扩展方法。这意味着您必须将 System.Net.Http.Json 添加到您的项目中,然后使用它

using System.Text.Json;
,否则您将收到编译错误。

另请注意,此示例为每个请求实例化一个 httpClient。不建议这样做。这种做法会在每次调用时强制建立新的连接,这需要新的 https 握手。相反,请使用单例或静态实例。有关如何正确实现此功能的完整详细信息,请参阅文档,或在此处观看我的视频:https://youtu.be/BA1e_ez8fwI?si=Tt0ppiIxoVOX57mA

var roomRequest = new RoomRequest() { EndDate = DateTime.Now.AddHours(2) };
RoomRequestResponse roomRequestResponse;

var apiKey = await this.DataStore.GetAppSetting("whereby-api");
HttpClient client = new HttpClient();

client.DefaultRequestHeaders.Authorization
             = new AuthenticationHeaderValue("Bearer", apiKey.Value);
var response = await client.PostAsJsonAsync("https://api.whereby.dev/v1/meetings", roomRequest);

string jsonString = await response.Content.ReadAsStringAsync();


RoomRequestResponse? returnValue=
    JsonSerializer.Deserialize<RoomRequestResponse>(jsonString);
© www.soinside.com 2019 - 2024. All rights reserved.