Java HTTP Request with Basic Auth

This is how you do a simple HTTP request with Java. These code performs the actual HTTP request and saves the response in a String variable.

URL url = new URL(address);
URLConnection conn = url.openConnection();
conn.setConnectTimeout(30000); // 30 seconds time out
String line = "";
StringBuffer sb = new StringBuffer();
BufferedReader input = new BufferedReader(new InputStreamReader(conn.getInputStream()) );
while((line = input.readLine())!=null)
  sb.append(line);
input.close();
String response = sb.toString();

If the HTTP server requires Baisc Auth this code will fail. To make it work for Basic Auth these 3 additional lines are required.

String user_pass = username + ":" + password;
String encoded = Base64.encodeBase64String( user_pass.getBytes() );
conn.setRequestProperty("Authorization", "Basic " + encoded);

The whole method looks like that:

public String getHttpResponse(String address, String username, String password) throws Exception {
  URL url = new URL(address);
  URLConnection conn = url.openConnection();
  conn.setConnectTimeout(30000); // 30 seconds time out

  if (username != null && password != null){
    String user_pass = username + ":" + password;
    String encoded = Base64.encodeBase64String( user_pass.getBytes() );
    conn.setRequestProperty("Authorization", "Basic " + encoded);
  }

  String line = "";
  StringBuffer sb = new StringBuffer();
  BufferedReader input = new BufferedReader(new InputStreamReader(conn.getInputStream()) );
  while((line = input.readLine()) != null)
    sb.append(line);
  input.close();
  return sb.toString();
}

Published by Robert Reiz

CEO @ VersionEye. Passionated software developer since 1998.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: