[java] Adding header for HttpURLConnection

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

This question is related to java http

The answer is


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


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

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


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

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

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