Quantcast
Channel: Active questions tagged header - Stack Overflow
Viewing all articles
Browse latest Browse all 795

Invoke Rest API with a custom header

$
0
0

I am trying to invoke a rest api. But I get 401 unauthorized. The same call works fine from C# and postman with the same token.

Here is a snippet of the code I am using:

$contentType = "application/json" try {       $response = Invoke-RestMethod -Uri $URL -Method Post -Headers @{Cookie = "token=xxxxxx"} -ContentType $contentType -Body $json        return $response.StatusCode}catch {             Write-Host "Error: $($_.Exception.Message)"             return $null     }

This is the C# code that is working:

HttpWebRequest webRequest;        HttpWebResponse response;        string URL ="https://apiurl/method";        string header ="Cookie";        string token ="token=xxxxxx";        webRequest = (HttpWebRequest)WebRequest.Create(URL);        webRequest.Headers.Add(header, token);        webRequest.Method = "POST";        webRequest.ContentType = "application/json";        using (var streamWriter = new StreamWriter(webRequest.GetRequestStream()))        {             var attributes= new RestAttributes();             string json = new JavaScriptSerializer().Serialize(attributes);             streamWriter.Write(json);        }        response = (HttpWebResponse)webRequest.GetResponse();        Stream streamResponse = response.GetResponseStream();        StreamReader streamReader = new StreamReader(streamResponse);        string Response = streamReader.ReadToEnd();        return response.StatusCode.ToString();

Tried encoding the token, also tried Invoke-WebRequest. Nothing works.


Viewing all articles
Browse latest Browse all 795

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>