sanczez
sanczez

Reputation: 223

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.

Upvotes: 22

Views: 77336

Answers (5)

Yoon5oo
Yoon5oo

Reputation: 514

As Gabe Rogan mentioned, "The method authenticate from BasicScheme has been deprecated".

An alternative way to do this,

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

Upvotes: 0

TienLuong
TienLuong

Reputation: 1125

  • DefaultHttpClient deprecated
  • addHeader must have 2 parameters

Updated code block using 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();

Upvotes: 1

kairouan2020
kairouan2020

Reputation: 151

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";
}

Upvotes: 8

Josef Pfleger
Josef Pfleger

Reputation: 74527

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.

Upvotes: 58

CommonsWare
CommonsWare

Reputation: 1006744

Use HttpClient. Documentation for performing downloads with HTTP AUTH is here. Documentation for getting a string result is here. Then, parse your string (ideally using SAX, though, not DOM).

Upvotes: 2

Related Questions