This article is participating in the Java Topic Month – Java Debug Notes event. See < activity link > for details.

How do I add a header to an HttpURLConnection?

I’m trying to add the header to the request using HttpUrlConnection, but the setRequestProperty() method doesn’t seem to work. The server did not receive any requests 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);
        }
Copy the code

Answer 1:

I have used the following code in the past and have used it for authentication

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);
Copy the code

Answer 2:

Your code is fine, and you can use the following code to achieve the same requirements

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;
}
Copy the code

If authorization succeeds, 200 is returned

Answer 3:

By using RestAssurd, you can also:

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
Copy the code