首先介绍POST,然后介绍GET。
POST:
主要用到了四个东西HttpWebRequest,Stream,StreamReader,HttpWebResponse。介绍一下下面的代码:
1.首先用CreateHttp通过传进来的url地址新建一个HttpWebRequest request,接下来设置了request的一些属性。
2.为了向request里写入外面传进的postDataStr,用GetRequestStream获取request的stream,将postDataStr写入。
3.根据request获得HttpWebResponse response,从response中获得receiveStream。
4.最后使用一个StreamReader对象streamReader将stream中的数据读到字符串中并返回。
internal static string HttpPost(string Url, string postDataStr)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(Url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
Stream requestStream = request.GetRequestStream();
requestStream.Write(Encoding.UTF8.GetBytes(postDataStr), 0, Encoding.UTF8.GetByteCount(postDataStr));
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream receiveStream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(receiveStream, Encoding.UTF8);
string responseString = streamReader.ReadToEnd();
requestStream.Close();
receiveStream.Close();
response.Close();
streamReader.Close();
return responseString;
}
GET:
Get与Post类似,直接贴上代码
internal static string HttpGet(string url, string postDataStr)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(url + (postDataStr == "" ? "" : "?") + postDataStr);
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream receiveStream = response
.GetResponseStream();
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
string retString = readStream.ReadToEnd();
receiveStream.Close();
readStream.Close();
return retString;
}
POST测试:
static void Main(string[] args)
{
string postDataStr = "postData=xuan";
string url = "https://www.baidu.com";
Console.WriteLine(HttpOperation.HttpPost(url,postDataStr));
Console.ReadKey();
}
GET测试:
static void Main(string[] args)
{
string url = "http://blog.csdn.net/qq5558809xv/article/details/53160234";
Console.WriteLine(HttpOperation.HttpGet(url,""));
Console.ReadKey();
}