Thursday, March 11, 2021

Java Http Request

public static String GetWebResponse(String urlStr) throws Exception
{
URL url = new URL(urlStr);

// Open a connection(?) on the URL(??) and cast the response(???)
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

// Now it's "open", we can set the request method, headers etc.
connection.setRequestMethod("GET");

//String baseAuth=BuildBaseAuthentication("testuser","testpwd");
connection.setRequestProperty("Authorization", "Basic aGV3bTpOb3YxMCE/IQ==");
connection.setRequestProperty("Content-Type", "application/json");

BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();


return content.toString();
}


public static String BuildBaseAuthentication(String name, String password)
{
String authString = name + ":" + password;
byte[] authEncBytes = Base64.getEncoder().encode((authString.getBytes()));
String authStringEnc = new String(authEncBytes);
System.out.println("Base64 encoded auth string: " + authStringEnc);
return "Basic " +authStringEnc;

} 

No comments: