与基本身份验证HTTP请求 [英] HTTP requests with basic authentication
问题描述
我必须从HTTP服务器与 HTTP基本身份验证,下载并解析XML文件。现在我做的是这样的:
I have to download and parse XML files from http server with HTTP Basic authentication. Now I'm doing it this way:
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();
不过,以这种方式我不能得到XML(或我只是简单地不知道的)的服务器文档HTTP认证。
But in that way I can't get xml (or I'm just simply not aware of that ) document from server with http authentication.
我将非常感激,如果你能告诉我要达到我的目标,最好的和最简单的方法。
I will be really grateful if you can show me the best and easiest way to reach my goal.
推荐答案
您可以使用<一个href="http://developer.android.com/reference/java/net/Authenticator.html"><$c$c>Authenticator$c$c>.例如:
You can use an Authenticator
. For example:
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
"user", "password".toCharArray());
}
});
这将设置默认身份验证
和所有的请求将被使用。显然,设置是更复杂的时候,你并不需要凭据的所有请求或多个不同的凭证,也许在不同的线程。
This sets the default Authenticator
and will be used in all requests. Obviously the setup is more involved when you don't need credentials for all requests or a number of different credentials, maybe on different threads.
另外,您可以使用<一个href="http://developer.android.com/reference/org/apache/http/impl/client/DefaultHttpClient.html"><$c$c>DefaultHttpClient$c$c>凡与基本的HTTP认证的GET请求将类似于:
Alternatively you can use a DefaultHttpClient
where a GET request with basic HTTP authentication would look similar to:
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()
我建议使用后者,因为它给你更多的控制(如方法,头,超时等),在您的要求。
I recommend using the latter because it gives you a lot more control (e.g. method, headers, timeouts, etc.) over your request.
这篇关于与基本身份验证HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!