C#中使用HttpWebRequest发送网络请求,HttpWebResponse接收网络请求
具体如下:
一、HttpWebRequest
1、HttpWebRequest 发送Get请求:
//请求的地址
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("https://api.qq.com/tok?type=cli");
//请求方法
req.Method = "GET";
//数据内容类型
req.ContentType = "application/json";
//请求的超时时间 10秒还没出来就超时
req.Timeout = 10000;
//接收响应的结果
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
//接收HTTP响应的数据流
using (Stream resStream = response.GetResponseStream())
{
//把数据流存入StreamReadr,选用编码格式
using (StreamReader reader = new StreamReader(resStream, Encoding.UTF8))
{
//通过ReadToEnd()把整个HTTP响应作为一个字符串取回,
//也可以通过 StreamReader.ReadLine()方法逐行取回HTTP响应的内容。
string responseContent = reader.ReadToEnd().ToString();
}
}
HTTP 内容类型(Content-Type)
普通文本 "text/plain";
JSON字符串 "application/json";
未知类型(数据流) "application/octet-stream";
表单数据(键值对) "application/x-www-form-urlencoded";
表单数据(键值对)编码方式为 gb2312 "application/x-www-form-urlencoded;charset=gb2312";
表单数据(键值对)编码方式为 utf-8 "application/x-www-form-urlencoded;charset=utf-8";
多分部数据 "multipart/form-data";
提交的时候可以说明编码的方式,用来使对方服务器能够正确的解析。
该ContentType的属性包含请求的媒体类型。分配给ContentType属性的值在请求发送Content-typeHTTP标头时替换任何现有内容。
要清除Content-typeHTTP标头,请将ContentType属性设置为null。
2、HttpWebRequest 发送Post请求:
public static string HttpPost(string Url, string postDataStr)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
request.ContentType = "application/json";//"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;
}
|
请发表评论