通过HttpWebRequest post数据的问题

flame100 2018-08-07 11:10:36
工作上需要通过http协议往服务器post一条json字符串,服务器会返回成功或者故障信息,网络上找了些HttpWebRequest例子,都遇到同一种现象,相同的代码,如果我电脑打开Fiddler 4软件,执行结果能够成功,但我关闭Fiddler 4情况下,返回提示信息是“发送数据不能为空”。
不知道问题的原因,请求帮助,谢谢
贴一段代码,c#
public static string HttpPost(string url, string param)
{
byte[] byteArray = Encoding.UTF8.GetBytes(param);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "text/xml;charset=UTF-8";
webRequest.ContentLength = byteArray.Length;
Stream newStream = webRequest.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
StreamReader php = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string phpend = php.ReadToEnd();
return phpend;
}
...全文
169 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
圣殿骑士18 2018-08-09
  • 打赏
  • 举报
回复
之前也曾经碰到过HttpAnalyzer工具会影响效果的情况。最终肯定是代码上的问题,逐步调试吧,用try catch捕捉异常。
catch部分注意捕捉一下innerexception,可能能得到有用的信息
catch (WebException ex)
{
string errorMessage = ex.Message;

//需判断response是否==null
WebResponse exResponse = ex.Response;
if (exResponse == null)
{
throw;
}
else
{
receiveStreamOut = exResponse.GetResponseStream();
srOut = new StreamReader(receiveStreamOut, encoding.IsNullOrEmpty() ? Encoding.UTF8 : Encoding.GetEncoding(encoding));
string result = srOut.ReadToEnd();
exResponse.Close();

//此处将错误信息和json信息同时返回
throw new CustomWebException(result, url, ex);
}
}
吹风的兔子 2018-08-09
  • 打赏
  • 举报
回复
https://www.cnblogs.com/shuxiaolong/p/20160717_0305.html
《『备忘』HttpWebRequest 在 POST 提交时, 标头(Headers)丢失原因》

一定不要设置 HttpWebRequest.ContentLength 这个字段。手动设置 这个字段 将导致 标头(Header)丢失【尤其是 自定义标头丢失】。

—— 楼主:结贴给分吧。
token不能为空 2018-08-09
  • 打赏
  • 举报
回复
看代码没看出问题,建议你断点打到
newStream.Write(byteArray, 0, byteArray.Length);
这行调试一下,还有就是代码用个try catch 包一下,看看有没有异常

但是你说 打开Fiddler 4 可以正常使用,这点我也无法理解

111,093

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧