httpWebRequest怎么POST,JSON数据
1个回答
2016-03-08 · 知道合伙人数码行家
huanglenzhi
知道合伙人数码行家
向TA提问 私信TA
知道合伙人数码行家
采纳数:117538
获赞数:517184
长期从事计算机组装,维护,网络组建及管理。对计算机硬件、操作系统安装、典型网络设备具有详细认知。
向TA提问 私信TA
关注
展开全部
/// <summary>
/// 返回JSon数据
/// </summary>
/// <param name="JSONData">要处理的JSON数据</param>
/// <param name="Url">要提交的URL</param>
/// <returns>返回的JSON处理字符串</returns>
public string GetResponseData(string JSONData,string Url)
{byte[] bytes = Encoding.UTF8.GetBytes(JSONData)
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
request.ContentLength = bytes.Length;
request.ContentType = "text/xml";
Stream reqstream = request.GetRequestStream();
reqstream.Write(bytes, 0, bytes.Length);
//声明一个HttpWebRequest请求
request.Timeout = 90000;
//设置连接超时时间
request.Headers.Set("Pragma", "no-cache");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream streamReceive = response.GetResponseStream();
Encoding encoding = Encoding.UTF8;
StreamReader streamReader = new StreamReader(streamReceive, encoding);
string strResult = streamReader.ReadToEnd();
streamReceive.Dispose();
streamReader.Dispose();
return strResult;
}
如果不通过request.write()的方式向接口post数据,将request.ContentLength属性设置为0,让后去掉request.write()方法即可!
/// 返回JSon数据
/// </summary>
/// <param name="JSONData">要处理的JSON数据</param>
/// <param name="Url">要提交的URL</param>
/// <returns>返回的JSON处理字符串</returns>
public string GetResponseData(string JSONData,string Url)
{byte[] bytes = Encoding.UTF8.GetBytes(JSONData)
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
request.ContentLength = bytes.Length;
request.ContentType = "text/xml";
Stream reqstream = request.GetRequestStream();
reqstream.Write(bytes, 0, bytes.Length);
//声明一个HttpWebRequest请求
request.Timeout = 90000;
//设置连接超时时间
request.Headers.Set("Pragma", "no-cache");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream streamReceive = response.GetResponseStream();
Encoding encoding = Encoding.UTF8;
StreamReader streamReader = new StreamReader(streamReceive, encoding);
string strResult = streamReader.ReadToEnd();
streamReceive.Dispose();
streamReader.Dispose();
return strResult;
}
如果不通过request.write()的方式向接口post数据,将request.ContentLength属性设置为0,让后去掉request.write()方法即可!
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询