0

访问 RESTful Web 服务时出现未经授权的错误。我的示例程序如下所示。

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);

我的凭据是正确的。

任何人都可以帮助解决这个问题。

谢谢。

4

1 回答 1

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 流量(Headers,body)

运行 Java 客户端代码并记录 HTTP 流量(Headers,body)

分析并修复差异

于 2013-01-15T10:30:42.793 回答