2013-01-15 33 views
0

訪問寧靜的Web服務時出現未授權錯誤。我的示例程序看起來像這樣。使用正確憑據訪問基於休息的Web服務時的響應代碼401

public static void main(String[] args){ 
     // Use apache commons-httpclient to create the request/response 
     HttpClient client = new HttpClient(); 
     Credentials defaultcreds = new UsernamePasswordCredentials("aaa", "cdefg"); 
     client.getState().setCredentials(AuthScope.ANY, defaultcreds); 


     GetMethod method = new GetMethod(
       "http://localhost:8080/userService/usersByID/1234"); 
     try { 
      client.executeMethod(method); 
      InputStream in = method.getResponseBodyAsStream(); 
      // Use dom4j to parse the response and print nicely to the output stream 
      BufferedReader reader = new BufferedReader(new InputStreamReader(in)); 
      StringBuilder out = new StringBuilder(); 
      String line; 
      while ((line = reader.readLine()) != null) { 
       out.append(line); 
      } 
      System.out.println(out.toString()); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

我的憑據是正確的。我的Web服務將使用基本Http身份驗證。

我對認證範圍有疑問。

client.getState().setCredentials(AuthScope.ANY, defaultcreds); 

我的憑據是正確的。

任何人都可以幫助解決這個問題。

謝謝。

回答

1

首先通過瀏覽器檢查您的網址並驗證?這裏

提到修復401錯誤 - 一般

Each Web Server manages user authentication in its own way. A security officer (e.g. a Web Master) at the site typically decides which users are allowed to access the URL. This person then uses Web server software to set up those users and their passwords. So if you need to access the URL (or you forgot your user ID or password), only the security officer at that site can help you. Refer any security issues direct to them. 

If you think that the URL Web page *should* be accessible to all and sundry on the Internet, then a 401 message indicates a deeper problem. The first thing you can do is check your URL via a Web browser. This browser should be running on a computer to which you have never previously identified yourself in any way, and you should avoid authentication (passwords etc.) that you have used previously. Ideally all this should be done over a completely different Internet connection to any you have used before (e.g. a different ISP dial-up connection). In short, you are trying to get the same behaviour a total stranger would get if they surfed the Internet to the Web page. 

If this type of browser check indicates no authority problems, then it is possible that the Web server (or surrounding systems) have been configured to disallow certain patterns of HTTP traffic. In other words, HTTP communication from a well-known Web browser is allowed, but automated communication from other systems is rejected with an 401 error code. This is unusual, but may indicate a very defensive security policy around the Web server. 

手動修復

從瀏覽器中點擊URL和記錄HTTP流量(頭,體)

運行Java客戶端代碼並記錄HTTP流量(標題,正文)

分析並修復差異

+1

感謝您的回覆。我可以通過瀏覽器訪問網址。我可以完美地打開它。 – Patan

+0

分析瀏覽器的HTTP流量,你的java代碼找出差異 – TheWhiteRabbit

相關問題