2015-06-12 58 views
0

以下是方法。我一直在研究這一段時間,並修改標題值等。它仍然會出現401 Unauthorized Exception,除非我包含內容長度標題,然後會出現另一個錯誤,說明內容長度標題無效。有沒有人有任何想法如何解決這個問題?其他API嘗試POST時返回401未授權的異常

我也試過通過HTTPWebRequest來做這件事。

Web客戶端代碼:

public void postResponse(string supplierid, string token, string geturl, string lineid) 
     { 
       lineid = lineid.Trim(); 
       //string postdata = ("{'supplier_id':'"+supplierid+"', 'token':'"+token+"','ci_lineitem_ids':["+lineid+"]}"); 

      try 
      { 
       string postdata = ("{'supplier_id':'"+supplierid+"','token':'"+token+"','ci_lineitem_ids':["+lineid+"]}"); 

       Console.WriteLine(postdata); 
       WebClient postWithParamsClient = new WebClient(); 
       postWithParamsClient.UploadStringCompleted += 
      new UploadStringCompletedEventHandler(postWithParamsClient_UploadStringCompleted); 
       postWithParamsClient.UseDefaultCredentials = true; 
       postWithParamsClient.Credentials = new NetworkCredential(supplierid, token); 
       postWithParamsClient.Headers.Add("Content-Type", "application/json"); 

       string headerlength = postdata.Length.ToString(); 
       //postWithParamsClient.Headers["Content-Length"] = headerlength; 
       postWithParamsClient.UploadStringAsync(new Uri(geturl), 
                 "POST", 
                 postdata); 

      } 
      catch (Exception e) 
      { 
       Console.WriteLine(e); 
      } 


     } 

HttpWebRequest的

   ASCIIEncoding encoding = new ASCIIEncoding(); 
       Byte[] postBytes = encoding.GetBytes(postdata); 
       // used to build entire input 
       StringBuilder sb = new StringBuilder(); 

       // used on each read operation 
       byte[] buf = new byte[8192]; 

       HttpWebRequest request = (HttpWebRequest)WebRequest.Create(geturl); 
       request.Credentials = new NetworkCredential(supplierid, token); 
       request.Method = "POST"; 
       request.ContentLength = postBytes.Length; 
       request.ContentType = "application/json"; 

       Stream postStream = request.GetRequestStream(); 
       postStream.Write(postBytes, 0, postBytes.Length); 
       postStream.Close(); 
+0

可能你可能需要明確設置一個標題,說明你正在使用基本認證。請參閱http://kristofmattei.be/2013/02/20/webclient-not-sending-credentials-heres-why/ –

+0

您也可以考慮使用restsharp,它大大簡化了這類事情。 – Wjdavis5

回答

0

你應該嘗試使用Fiddler看到你發送,並比較你的服務器的需求。檢查授權標題和您的憑證的有效性。我認爲這是第一件事