Reputation: 21
I tried to connect a REST API using the postman and it's always a good request. No problems.
But, in the rest implementation code I always receive the error "StatusCode: Unauthorized, Content-Type: text/plain; charset=utf-8, Content-Length: 0)".
I've tried many ways to do this but it never done.
//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;
In the postman
The server doesn't receive the Authorization token when I try to do it in the code.
Upvotes: 1
Views: 1859
Reputation: 21
I am using the HttpWebRequest but I think it's also possible using the RestClient.
I used the Fiddler to identify the headers in the postman request and then I reply this headers in the code.
The code below is working to me.
I will make some changes but that's it.
//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();
Upvotes: 1