如何在.net中模拟post方式提交json数据

 我来答
你猜我猜哇擦猜
2015-12-25 · TA获得超过2.8万个赞
知道大有可为答主
回答量:2万
采纳率:0%
帮助的人:6793万
展开全部
public class Httper
{
public string Post(string url, string data, EncodingType encodingType = EncodingType.UTF8)
{
string result = string.Empty;

if (string.IsNullOrEmpty(data))
{
data = string.Empty;
}

byte[] byteArray = Encoding.UTF8.GetBytes(data);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

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

request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36";

request.Timeout = 20000;

StreamReader sr = null;
try
{
using (Stream newStream = request.GetRequestStream())
{
newStream.Write(byteArray, 0, byteArray.Length);
//newStream.Close();
//获取响应
using (WebResponse response = request.GetResponse())
{
if (encodingType == EncodingType.GB2312)
{
sr = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("GB2312"));
}
else
{
sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
}

result = sr.ReadToEnd();
sr.Close();
}
}
}
catch
{
}
return result;
}

private static object _lockObj = new object();

public string Post(string url, string referer, string data, System.Net.CookieContainer cookie, HTTPMothedType httpMothodType = HTTPMothedType.POST)
{
string result = null;

if (string.IsNullOrEmpty(data))
{
data = string.Empty;
}

byte[] byteArray = Encoding.UTF8.GetBytes(data); // 转化

HttpWebRequest webRequest2 = (HttpWebRequest)WebRequest.Create(url);

if (cookie != null)
{
webRequest2.CookieContainer = cookie;
}

webRequest2.Referer = referer;

webRequest2.Method = httpMothodType.ToString();//"POST";

//webRequest2.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1";
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式