如何使用HttpWebRequest发布数据? [英] How can I Post data using HttpWebRequest?

查看:74
本文介绍了如何使用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

有人可以帮我告诉我如何将数据添加到POST吗?

Can someone help and tell me how I can add data to the POST ?

推荐答案

您可以这样做

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

但是我建议您在这种情况下使用 HttpClient 而不是 HttpWebRequest

but I suggest you use HttpClient rather than HttpWebRequest in this case

这篇关于如何使用HttpWebRequest发布数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆