十五、API请求接口-远程服务器返回错误: (400) 错误的请求错误

时间:2021-08-30 18:21:56

一、远程服务器返回错误: (400) 错误的请求错误

捕获异常查看具体错误

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text; namespace Test
{ class Program
{ static void Main(string[] args)
{
string url = "http://www.baidus.com";
string contentType = "application/x-www-form-urlencoded";
int timeOut = ;
string parms = "";
int encoding = ;
HttpWebRequest(url, parms, encoding, contentType, timeOut);
} public static void HttpWebRequest(string url, string parms, int encoding, string contentType = "application/x-www-form-urlencoded", int timeOut = )
{
try
{
string result = string.Empty;
var mRequest = (HttpWebRequest)WebRequest.Create(url);
//相应请求的参数
var data = Encoding.GetEncoding(encoding).GetBytes(parms);
mRequest.Method = "Post";
mRequest.ContentType = contentType;
mRequest.ContentLength = data.Length;
mRequest.Timeout = timeOut;
mRequest.KeepAlive = true;
mRequest.ProtocolVersion = HttpVersion.Version10;
//请求流
var requestStream = mRequest.GetRequestStream();
requestStream.Write(data, , data.Length);
requestStream.Close();
//响应流
var mResponse = mRequest.GetResponse() as HttpWebResponse;//此位置进入catch(403)
var responseStream = mResponse.GetResponseStream();//
if (responseStream != null)
{
var streamReader = new StreamReader(responseStream, Encoding.GetEncoding(encoding));
//获取返回的信息
result = streamReader.ReadToEnd();
streamReader.Close();
responseStream.Close();
}
}
catch (System.Net.WebException ex)
{
string result = string.Empty;
//响应流
var mResponse = ex.Response as HttpWebResponse;
var responseStream = mResponse.GetResponseStream();
if (responseStream != null)
{
var streamReader = new StreamReader(responseStream, Encoding.GetEncoding(encoding));
//获取返回的信息
result = streamReader.ReadToEnd();
streamReader.Close();
responseStream.Close();
}
result = "获取数据失败,请重试!" + url + ex.ToString() + " 返回数据" + result;
}
} } }