下面有代码,问题描述:一个web地址,本代码在控制台已经测试成功,浏览器访问正常,但是web程序就没成功过,一直报上面的问题
一个web地址,我再控制台已经成功了,但是web的请求每次都不成功,报上面的错,贴代码
public string JobFunctionRequest(string url, string xmlcontent, string encode)
{
try
{
Encoding encoding = Encoding.GetEncoding(encode);
byte[] data = encoding.GetBytes(xmlcontent);
// 准备请求,设置参数
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.3 Safari/535.19";
request.ContentLength = data.Length;
using (Stream writer = request.GetRequestStream())
{
writer.Write(data, 0, data.Length);
writer.Close();
writer.Dispose();
}
//发送请求并获取相应回应数据
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
Stream instream = response.GetResponseStream();
StreamReader sr = new StreamReader(instream, encoding);
//返回结果网页(html)代码
string content = sr.ReadToEnd();
sr.Close();
return content;
}
catch (Exception ex)
{
LogHelper.SaveLog(System.DateTime.Now.ToString() + "\r\n" + xmlcontent +"\r\n"+ ex);
return "3|其他错误. HttpWebRequest Send Failed." + ex.Message;
}
}
是不是要加response.End()?
Request或者Response没有释放掉。。最好dispose掉
郁闷了半天,最后用client解决了,写的代码简单(真心不觉得比这个好)。