【问题标题】:it's working in postman web and it does not work in the code它在邮递员网络中工作,但在代码中不起作用
【发布时间】:2019-09-11 17:27:56
【问题描述】:

我尝试使用邮递员连接 REST API,这始终是一个很好的请求。没问题。

但是,在其余的实现代码中,我总是收到错误“StatusCode: Unauthorized, Content-Type: text/plain; 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;

邮递员

当我尝试在代码中执行此操作时,服务器未收到授权令牌。

【问题讨论】:

  • 服务器无法判断您是使用 Postman 还是 C# 或其他任何东西来发布到它。因此,如果您比较 HTTP 请求,找出差异,这可能是导致他们的服务器对待来自您的代码的请求与来自 Postman 的请求不同的原因。请特别注意请求标头,例如用户代理。
  • 使用像 wrieshark 或 fiddler 这样的嗅探器,并将邮递员中的 http 标头与不起作用的 c# 代码进行比较。解决方案是让 c# http headers 看起来和 postman 完全一样。
  • 您能否告诉我们您是如何在代码中创建授权的。
  • 当我尝试在代码中执行时,服务器没有收到令牌。
  • 我会努力去做的。 @jdweng​​span>

标签: c# rest postman


【解决方案1】:

我正在使用 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();


【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-25
    • 2020-08-18
    • 1970-01-01
    • 2018-02-09
    • 2019-10-02
    • 2016-10-23
    • 2019-08-04
    相关资源
    最近更新 更多