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

jfgube3f  于 2023-11-20  发布在  .NET
关注(0)|答案(9)|浏览(132)

令我惊讶的是,在.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,并从静态类Http上的Post方法返回响应。
既然我们没有这么简单的东西,下一个最好的解决方案是什么?
如何发送一个包含数据的HTTP POST并获取响应的内容?

qmb5sa22

qmb5sa221#

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

oalqel3c

oalqel3c2#

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

}

字符串

eanckbw9

eanckbw93#

使用WebRequest。从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();
}

字符串

hjqgdpho

hjqgdpho4#

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

字符串

0kjbasz6

0kjbasz65#

就我个人而言,我认为最简单的方法来做一个http帖子,并获得响应是使用WebClient类。这个类很好地抽象了细节。在MSDN文档中甚至有一个完整的代码示例。
http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.80).aspx
在您的例子中,您需要的是EscheradData()方法(同样,文档中包含了代码示例)
http://msdn.microsoft.com/en-us/library/tdbbwh0a(VS.80).aspx
mixadString()可能也可以工作,它将其抽象到另一个级别。
http://msdn.microsoft.com/en-us/library/system.net.webclient.uploadstring(VS.80).aspx

rkkpypqq

rkkpypqq6#

考虑到其他答案都是几年前的,目前我的想法可能会有所帮助:

最简单的方法

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

xesrikrc

xesrikrc7#

我知道这是一个古老的故事,但希望它能帮助一些人。

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

字符串

xxb16uws

xxb16uws8#

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

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

字符串

du7egjpx

du7egjpx9#

下面是一个.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);

字符串

相关问题