Web Api HttpWebRequest 请求 Api 及 异常处理

时间:2022-09-03 17:12:08
            HttpWebRequest request = WebRequest.CreateHttp(url);

            request.Method = "post";
request.Headers.Add(HttpRequestHeader.Authorization, "password mima");
request.Headers.Add("Cookie", "Cookie信息");
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"; //request.ContentType = "application/json";
//string data = JsonConvert.SerializeObject(new
//{
// Id = 1,
// Name = "中+文",//JSON格式传递参数,"+"号依然是"+"
// Age = 100
//}); request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8"; // application/x-www-form-urlencoded 请求方式
// form 表示参数格式是 form 表单的格式
// urlencoded 表示该参数经过了 url 编码,注意:是经过了,而不是需要进行
string data = "id=1&name=中+文&age=100";
var bytes = Encoding.UTF8.GetBytes(data);
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, , bytes.Length);
requestStream.Close();
var response = request.GetResponse();
var sm = response.GetResponseStream();
var str = string.Empty;
using (StreamReader reader = new StreamReader(sm, Encoding.UTF8))
{
str = reader.ReadToEnd();
}
var person = JsonConvert.DeserializeObject<dynamic>(str);
Console.WriteLine(person.Id);//1 //服务器接收到请求后,识别出是"application/x-www-form-urlencoded"格式,
//便认为参数中的"中+文"是经过了 url 编码,
//因此,会自动 urldecode 解码
//所以 "+" 变成了 " ".
Console.WriteLine(person.Name);//中 文
Console.WriteLine(person.Age);//

补充:

如果API 返回的是 400,比如: return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "没有文件耶,哥们!");

那么  var response = request.GetResponse(); 这句话直接会抛出异常

那么,我们如何能接收到返回的信息 : "没有文件耶,哥们!" 这句话呢?

答案是 try catch,代码如下:

            var result = string.Empty;
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
result = sr.ReadToEnd();
}
}
catch (WebException ex)
{
var errorSr =new StreamReader(ex.Response.GetResponseStream());
result = errorSr.ReadToEnd();
}
return result;

Web Api HttpWebRequest 请求 Api 及 异常处理