簡體   English   中英

在 c# WebResponse response = request.GetResponse() 上出現未經授權的錯誤;

[英]Getting Unauthorized error on c# WebResponse response = request.GetResponse();

在 C# 上執行 GET 請求時出現授權錯誤,但如果我使用郵遞員嘗試它,它的返回就好了。

這是我的 c# 代碼:

url = @"http://somesource.com/api/v10/" + url;
WebRequest request = WebRequest.Create(url);
request.Headers.Add("Authorization", "Token 3e68409924cc57ff07a8e29a18341fd99d3fba91ds");
request.Method = "GET";
request.Timeout = TimeO; 


      try { 
           WebResponse response = request.GetResponse();
           status = ((HttpWebResponse)response).StatusDescription.ToString();


           if (status != "OK")
           Log.WriteLog(module, "Response x:: " + status);

          Stream dataStream = response.GetResponseStream();
          StreamReader reader = new StreamReader(dataStream);
          dataResponse = reader.ReadToEnd();
          reader.Close();
          dataStream.Close();
          response.Close();
      } catch (WebException ex)
        {
          dataResponse = "{\"Error\":true,\"Update\":false,\"Msg\":\"RQ x:: " + ex.Message + "\"}";
          Log.WriteLog(module, dataResponse);
      }

它返回The remote server returned an error: (401) Unauthorized.

but when I try using the same url + header with Authorization = "Token 3e68409924cc57ff07a8e29a18341fd99d3fba91ds" on post man as GET request, it returns json data just fine.

雖然如果我不發送 postman 上的標題,我會得到

{
    "detail": "Authentication credentials were not provided."
}

如果我故意將令牌設置錯誤,這就是我得到的:

{
    "detail": "Invalid token."
}

不同於 c# 程序記錄的內容。 這是

The remote server returned an error: (401) Unauthorized.

這可能是什么原因?

謝謝!

試試下面的代碼。 原文參考這里

string url = @"https://telematicoprova.agenziadogane.it/TelematicoServiziDiUtilitaWeb/ServiziDiUtilitaAutServlet?UC=22&SC=1&ST=2";
    WebRequest request = WebRequest.Create(url);
    request.Credentials = GetCredential();
    request.PreAuthenticate = true;       

     private CredentialCache GetCredential()
        {
            string url = @"https://telematicoprova.agenziadogane.it/TelematicoServiziDiUtilitaWeb/ServiziDiUtilitaAutServlet?UC=22&SC=1&ST=2";
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
            CredentialCache credentialCache = new CredentialCache();
            credentialCache.Add(new System.Uri(url), "Basic", new NetworkCredential(ConfigurationManager.AppSettings["ead_username"], ConfigurationManager.AppSettings["ead_password"]));
            return credentialCache;
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM