HttpWebRequest.GetResponse()错误,401错误(未经授权)

时间:2017-03-21 20:30:36

标签: json.net httpwebrequest httpwebresponse

我正在尝试执行HTTP PUT请求,但收到401错误(未经授权)。这是我的代码:

resources :equipment
get 'equipment', to: 'equipment#index', as: 'equipment' 

失败的行是:

string token = "<token>"; 
string putUrl = "https://<url>;
string payload = "{grading_standard_id:166}";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(putUrl);
request.Headers[HttpRequestHeader.Authorization] = "Bearer " + token;
request.Method = "PUT";
request.ContentType = "application/json";
string serializedObject = JsonConvert.SerializeObject(payload);
try
{
    using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
    {
        writer.Write(serializedObject);
    }
    HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // ERROR LINE
    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
    {
        string responseText = reader.ReadToEnd();
    }
}
catch (Exception ex)
{
    string msg = ex.Message;
    throw ex;
}

代码使用授权令牌在请求对象上设置标头;我不明白为什么不在这里进行身份验证。我尝试将请求对象的身份验证更改为

  

request.UseDefaultCredentials = true; request.PreAuthenticate = true;

在我进行GetResponse()调用之前,但是这个错误消失了,说在流写入后无法更改设置。

我从另一个stackoverflow post中获取了大部分代码。经过谷歌搜索一段时间后,我发现没有任何帮助。任何援助将不胜感激。谢谢。

0 个答案:

没有答案