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