使用基本认证进行HTTP请求

22

我需要从HTTP服务器下载并解析XML文件,同时使用HTTP基本身份验证。现在我是这样做的:

URL url = new URL("http://SERVER.WITHOUT.AUTHENTICATION/some.xml");
     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
     DocumentBuilder db = dbf.newDocumentBuilder();
     Document doc = db.parse(new InputSource(url.openStream()));
     doc.getDocumentElement().normalize();

但是这样我无法通过HTTP身份验证从服务器获取XML文档(或者我只是简单地不知道如何获取)。

如果你能向我展示达成目标的最佳且最简单的方法,我将非常感激。


相关:https://dev59.com/Z3RB5IYBdhLWcg3w1Kle - AlikElzin-kilaka
5个回答

58

您可以使用 Authenticator。例如:

Authenticator.setDefault(new Authenticator() {
 @Override
        protected PasswordAuthentication getPasswordAuthentication() {
         return new PasswordAuthentication(
   "user", "password".toCharArray());
        }
});

这将设置默认的Authenticator,并将在所有请求中使用。当您不需要所有请求或多个不同凭据(也许在不同的线程上)时,显然设置会更加复杂。

或者,您可以使用DefaultHttpClient,其中具有基本HTTP身份验证的GET请求将类似于:

HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://foo.com/bar");
httpGet.addHeader(BasicScheme.authenticate(
 new UsernamePasswordCredentials("user", "password"),
 "UTF-8", false));

HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity responseEntity = httpResponse.getEntity();

// read the stream returned by responseEntity.getContent()

我建议使用后者,因为它可以让你对请求拥有更多的控制权(例如方法、头信息、超时等)。


现在,我遇到了107无效的JSON代码错误。我已经在JSON Lint上检查过我的JSON,它是正确的。那么,如何摆脱这个错误。谢谢。 - Kaveesh Kanwal
明白了伙计!我本来在做一个POST请求,但是应该用GET请求。 - Kaveesh Kanwal

8
public String reloadTomcatWebApplication(String user, String pwd, String urlWithParameters, boolean returnResponse) {
    URL url = null;
    try {
        url = new URL(urlWithParameters);
    } catch (MalformedURLException e) {
        System.out.println("MalformedUrlException: " + e.getMessage());
        e.printStackTrace();
        return "-1";
    }

    URLConnection uc = null;
    try {
        uc = url.openConnection();
    } catch (IOException e) {
        System.out.println("IOException: " + e.getMessage());
        e.printStackTrace();
        return "-12";
    }


    String userpass = user + ":" + pwd;
    String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());

    uc.setRequestProperty("Authorization", basicAuth);
    InputStream is = null;
    try {
        is = uc.getInputStream();
    } catch (IOException e) {
        System.out.println("IOException: " + e.getMessage());
        e.printStackTrace();
        return "-13";
    }
    if (returnResponse) {
        BufferedReader buffReader = new BufferedReader(new InputStreamReader(is));
        StringBuffer response = new StringBuffer();

        String line = null;
        try {
            line = buffReader.readLine();
        } catch (IOException e) {
            e.printStackTrace();
            return "-1";
        }
        while (line != null) {
            response.append(line);
            response.append('\n');
            try {
                line = buffReader.readLine();
            } catch (IOException e) {
                System.out.println(" IOException: " + e.getMessage());
                e.printStackTrace();
                return "-14";
            }
        }
        try {
            buffReader.close();
        } catch (IOException e) {
            e.printStackTrace();
            return "-15";
        }
        System.out.println("Response: " + response.toString());
        return response.toString();
    }
    return "0";
}

1
我更喜欢这个变体,因为它不依赖于外部API,并且特定于查询。 - Julien Kronegg

2
使用HttpClient。执行HTTP AUTH下载的文档在这里。获取字符串结果的文档在这里。然后,解析您的字符串(最好使用SAX,而不是DOM)。

1
  • DefaultHttpClient已经废弃
  • addHeader必须有2个参数

使用HttpClient 4.5.2更新的代码块

HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet("https://test.com/abc.xyz");
httpGet.addHeader("Authorization", BasicScheme.authenticate(new UsernamePasswordCredentials("login", "password"), "UTF-8"));

HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity responseEntity = httpResponse.getEntity();

BasicScheme 中的 authenticate 方法已被弃用。 - Gabe Rogan

0
正如Gabe Rogan所提到的,“BasicScheme中的authenticate方法已被弃用”。
另一种替代方法是,
HttpRequestBase hrb = new HttpGet(req.getUrl()); // should be your URL    
UsernamePasswordCredentials Credential= new UsernamePasswordCredentials("id", "password");
Header header = new BasicScheme(StandardCharsets.UTF_8).authenticate(Credential, hrb, null);
hrb.addHeader(header);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接