您的位置:首页 > 理论基础 > 计算机网络

程序模拟HTTP请求

2016-05-09 10:23 651 查看
1. 使用HttpClient

前面拼接StringContent

string strContent = "client_id=client&client_secret=secret&grant_type=client_credentials";
HttpContent content = new StringContent(strContent, Encoding.UTF8, "application/x-www-form-urlencoded");


使用await:

public async void GetResponse()
{
HttpClient client = new HttpClient();
Url = "http://xxxx";
ClientInfo info = new ClientInfo();
Json = JsonConvert.SerializeObject(info, Settings);
HttpContent content = new StringContent(Json, Encoding.UTF8, "application/json");
using (var response = await client.PostAsync(Url, content))
{
var result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
}
}


这里可判断请求的状态

using (HttpClient client = new HttpClient())
{
using (var response = client.GetAsync(url))
{
response.Result.EnsureSuccessStatusCode();
var name = response.Result.Content.Headers.ContentDisposition.FileName.Replace("\"", "");
var buff = response.Result.Content.ReadAsByteArrayAsync().Result;
string filename = Path.Combine(path, name);
using (FileStream fs = new FileStream(filename, FileMode.OpenOrCreate))
{
fs.Write(buff, 0, buff.Length);
}
}
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: