常用 Http 的请求方法

第一次用markdown写博客,体验下

因为常用Http的几种请求方式,总结一下。

1.封装两个Http的最常用方法,叫做HttpHelper类。

HttpPost:

    public static string HttpPost(string Url, string postDataStr)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postDataStr.Length; StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);
writer.Write(postDataStr);
writer.Flush();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding; if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8"; //默认编码
}
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
string retString = reader.ReadToEnd();
return retString;
}

HttpGet:

    public static string HttpGet(string Url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8"; HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close(); return retString;
}

WebClientde中Post和Get:

	//Post
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/json";
client.Encoding = Encoding.UTF8;
result = client.UploadString(postUrl, "POST", postData);
}
//Get
var wc = new WebClient();
var jsonResult = wc.DownloadString(Url);

封装好Http的方法,直接传入Url和postData即可,不必每次创建request对象。

更新:the remote server returned an error (401) unauthorized

    var req = (HttpWebRequest)WebRequest.Create(tgtUrl);
req.UseDefaultCredentials = true;
req.PreAuthenticate = true;
req.Credentials = CredentialCache.DefaultCredentials;
var response = req.GetResponse();
var stream = req.GetRequestStream(); var wc = new WebClient();
//Set default credential, avoid unauthorize error
wc.Credentials = CredentialCache.DefaultCredentials;
wc.UseDefaultCredentials = true;
上一篇:如何用java写出无副作用的代码


下一篇:$.ajax 跨域请求 Web Api