简体   繁体   English

如何使用HttpWebRequest发布数据?

[英]How can I Post data using HttpWebRequest?

I have this HttpWebRequest : 我有这个HttpWebRequest

var request = HttpWebRequest.Create("http://example.com/api/Phrase/GetJDTO");
request.ContentType = "application/json";
request.Method = "POST";

But I need to add a payload to the body of the request like this: 但我需要在请求正文中添加一个有效负载,如下所示:

Jlpt = 2

Can someone help and tell me how I can add data to the POST ? 有人可以帮忙告诉我如何向POST添加数据吗?

You can do by this 你可以做到这一点

var request = HttpWebRequest.Create("http://example.com/api/Phrase/GetJDTO");

var postData = "Jlpt = 2";
var data = Encoding.ASCII.GetBytes(postData);

request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;

using (var stream = request.GetRequestStream())
{
    stream.Write(data, 0, data.Length);
}

var response = (HttpWebResponse)request.GetResponse();

var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

but I suggest you use HttpClient rather than HttpWebRequest in this case 但我建议你在这种情况下使用HttpClient而不是HttpWebRequest

if (data != null)
{
    request.ContentType = "application/json";
    using (var stream = new StreamWriter(request.GetRequestStream()))
    {
        var serialized = JsonConvert.SerializeObject(data);
        stream.Write(serialized);
    }
}
else
{
    request.ContentLength = 0;
}

where data is any object you want to send 其中data是您要发送的任何对象

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM