我尝试使用邮递员连接REST API,这始终是一个很好的请求。没问题。
但是,在其余的实现代码中,我总是收到错误“ StatusCode:未经授权,Content-Type:文本/纯文本; charset = utf-8,Content-Length:0)”。
我已经尝试了许多方法来做到这一点,但从未成功。
//url = url server
//authorization = Bearer .....
//body = text json
var client = new RestClient(url);
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/json");
request.AddHeader("authorization", authorization);
request.AddParameter("application/json", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var result = response.Content;
在邮递员中
当我尝试在代码中进行操作时,服务器未收到授权令牌。
答案 0 :(得分:0)
我正在使用HttpWebRequest,但我认为也可以使用RestClient。
我用Fiddler来识别邮递员请求中的标头,然后在代码中回复这些标头。
下面的代码对我有用。
我会做一些更改,仅此而已。
//url = url server
//authorization = Bearer .....
//body = text json
//bytesBody = body in byte[]
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.PreAuthenticate = true;
webRequest.Method = "POST";
webRequest.Headers["Cache-Control"] = "no-cache";
webRequest.Accept = "*/*";
webRequest.Headers["Accept-Encoding"] = "gzip, deflate, br";
webRequest.Headers["Accept-Language"] = "en-US,en;q=0.9,pt-BR;q=0.8,pt;q=0.7";
webRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36";
webRequest.ContentType = "application/json";
webRequest.ContentLength = bytesBody.Length;
webRequest.Headers["authorization"] = authorization;
//webRequest.Headers["Origin"] = "chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop";
webRequest.KeepAlive = true;
webRequest.ServicePoint.Expect100Continue = false;
webRequest.Host = host;
using (Stream dataStream = webRequest.GetRequestStream())
{
dataStream.Write(bytesBody, 0, bytesBody.Length);
dataStream.Flush();
dataStream.Close();
}
WebResponse response = webRequest.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
}
response.Close();