Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

java - HTTP requests with basic authentication

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...