具有基本身份验证的HTTP请求

san*_*zez 22 java android

我必须使用 HTTP基本身份验证从http服务器下载和解析XML文件.现在我这样做:

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();
Run Code Online (Sandbox Code Playgroud)

但是通过这种方式,我无法从具有http身份验证的服务器获取xml(或者我只是不知道).

如果你能告诉我实现目标的最佳和最简单的方法,我将非常感激.

Jos*_*ger 57

你可以使用Authenticator.例如:

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

这将设置默认值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()
Run Code Online (Sandbox Code Playgroud)

我推荐使用后者,因为它可以为您提供更多的控制(例如方法,标题,超时等).


小智 6

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";
}
Run Code Online (Sandbox Code Playgroud)