httpclient发送接受请求

需要注意三部分,request和参数的处理,响应数据。与请求相关的dll是System.Net。

核心代码:

private string Post(string requestUrlString, string data, string header)
{

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrlString);
request.Method = "POST";
request.ContentType = "text/html"; //内容类型
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Q312461; .NET CLR 1.0.3705)";

if (!header.IsNullOrEmpty())
{
request.Headers = new WebHeaderCollection();
request.Headers.Add(header);
}
string entity = string.Empty;
try
{
if (data != string.Empty)
{
#region 填充要post的内容
byte[] bytes = UnicodeEncoding.UTF8.GetBytes(data);
request.ContentLength = bytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
#endregion
}

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
entity = response.GetResponseStream().FromStreamToString();
}
}
}
catch (Exception ex)
{
LogHelper.WriteInfoLog(typeof(HttpClient),
string.Format("发送HTTP请求失败,URL:{0},Data:{1},Header:{2};{3};{4}",
requestUrlString, data, header, ex.Message, ex.StackTrace));
throw ex;
}

LogHelper.WriteInfoLog(typeof(HttpClient), "请求地址:" +
requestUrlString + "\n请求参数:" + data + "\nUser_Token:" + header + "\n请求返回:" + entity);

return entity;
}

posted on 2017-03-02 17:50  栖梧  阅读(159)  评论(0编辑  收藏  举报