Adding header for HttpURLConnection

JavaHttp

Java Problem Overview


I'm trying to add header for my request using HttpUrlConnection but the method setRequestProperty() doesn't seem working. The server side doesn't receive any request with my header.

HttpURLConnection hc;
	try {
		String authorization = "";
		URL address = new URL(url);
		hc = (HttpURLConnection) address.openConnection();
		
		
		hc.setDoOutput(true);
		hc.setDoInput(true);
		hc.setUseCaches(false);
		
		if (username != null && password != null) {
			authorization = username + ":" + password;
		}
		
		if (authorization != null) {
			byte[] encodedBytes;
			encodedBytes = Base64.encode(authorization.getBytes(), 0);
			authorization = "Basic " + encodedBytes;
			hc.setRequestProperty("Authorization", authorization);
		}

Java Solutions


Solution 1 - Java

I have used the following code in the past and it had worked with basic authentication enabled in TomCat:

URL myURL = new URL(serviceURL);
HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();

String userCredentials = "username:password";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));

myURLConnection.setRequestProperty ("Authorization", basicAuth);
myURLConnection.setRequestMethod("POST");
myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
myURLConnection.setRequestProperty("Content-Length", "" + postData.getBytes().length);
myURLConnection.setRequestProperty("Content-Language", "en-US");
myURLConnection.setUseCaches(false);
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);

You can try the above code. The code above is for POST, and you can modify it for GET

Solution 2 - Java

Just cause I don't see this bit of information in the answers above, the reason the code snippet originally posted doesn't work correctly is because the encodedBytes variable is a byte[] and not a String value. If you pass the byte[] to a new String() as below, the code snippet works perfectly.

encodedBytes = Base64.encode(authorization.getBytes(), 0);
authorization = "Basic " + new String(encodedBytes);

Solution 3 - Java

If you are using Java 8, use the code below.

URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;

String basicAuth = Base64.getEncoder().encodeToString((username+":"+password).getBytes(StandardCharsets.UTF_8));
httpConn.setRequestProperty ("Authorization", "Basic "+basicAuth);

Solution 4 - Java

Finally this worked for me

private String buildBasicAuthorizationString(String username, String password) {

	String credentials = username + ":" + password;
	return "Basic " + new String(Base64.encode(credentials.getBytes(), Base64.NO_WRAP));
}

Solution 5 - Java

Your code is fine.You can also use the same thing in this way.

public static String getResponseFromJsonURL(String url) {
	String jsonResponse = null;
	if (CommonUtility.isNotEmpty(url)) {
		try {
			/************** For getting response from HTTP URL start ***************/
			URL object = new URL(url);

			HttpURLConnection connection = (HttpURLConnection) object
					.openConnection();
			// int timeOut = connection.getReadTimeout();
			connection.setReadTimeout(60 * 1000);
			connection.setConnectTimeout(60 * 1000);
			String authorization="xyz:xyz$123";
			String encodedAuth="Basic "+Base64.encode(authorization.getBytes());
			connection.setRequestProperty("Authorization", encodedAuth);
			int responseCode = connection.getResponseCode();
			//String responseMsg = connection.getResponseMessage();

			if (responseCode == 200) {
				InputStream inputStr = connection.getInputStream();
				String encoding = connection.getContentEncoding() == null ? "UTF-8"
						: connection.getContentEncoding();
				jsonResponse = IOUtils.toString(inputStr, encoding);
				/************** For getting response from HTTP URL end ***************/

			}
		} catch (Exception e) {
			e.printStackTrace();

		}
	}
	return jsonResponse;
}

Its Return response code 200 if authorizationis success

Solution 6 - Java

With RestAssurd you can also do the following:

String path = baseApiUrl; //This is the base url of the API tested
    URL url = new URL(path);
    given(). //Rest Assured syntax 
            contentType("application/json"). //API content type
            given().header("headerName", "headerValue"). //Some API contains headers to run with the API 
            when().
            get(url).
            then().
            statusCode(200); //Assert that the response is 200 - OK

Solution 7 - Java

Step 1: Get HttpURLConnection object

URL url = new URL(urlToConnect);
HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();

Step 2: Add headers to the HttpURLConnection using setRequestProperty method.

Map<String, String> headers = new HashMap<>();

headers.put("X-CSRF-Token", "fetch");
headers.put("content-type", "application/json");
                
for (String headerKey : headers.keySet()) {
	httpUrlConnection.setRequestProperty(headerKey, headers.get(headerKey));
}

Reference link

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMinh-Ha LeView Question on Stackoverflow
Solution 1 - JavaCyril BeschiView Answer on Stackoverflow
Solution 2 - JavaJoseph CozadView Answer on Stackoverflow
Solution 3 - JavaChandubabuView Answer on Stackoverflow
Solution 4 - JavagoriView Answer on Stackoverflow
Solution 5 - JavapintuView Answer on Stackoverflow
Solution 6 - JavaEyal SoolimanView Answer on Stackoverflow
Solution 7 - JavaHari KrishnaView Answer on Stackoverflow