311

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);
        }
Charlie Brumbaugh
  • 219
  • 1
  • 5
  • 15
Minh-Ha Le
  • 3,225
  • 2
  • 14
  • 8
  • Works for me, how do you tell the header was sent and not received? – Tomasz Nurkiewicz Oct 04 '12 at 17:26
  • 3
    sorry if this sounds dumb, but where are you calling `connect()` on the URLConnection? – Vikdor Oct 04 '12 at 17:26
  • I'm not sure if this has an effect but you can try adding `connection.setRequestMethod("GET");` (or POST or whatever you want)? – noobed Oct 04 '12 at 18:20
  • 1
    You initialise `authorization` to the empty string. If either `username` or `password` is null, then `authorization` will be the empty string, not null. Therefore, the final `if` will get executed, but the `"Authorization"` property will be set to empty, seems to me. – zerzevul Apr 12 '19 at 12:07

8 Answers8

505

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

Mike
  • 14,010
  • 29
  • 101
  • 161
Cyril Beschi
  • 5,194
  • 1
  • 15
  • 5
  • 15
    A little addition for android developers (on API >= 8 a.k.a 2.2): android.util.Base64.encode(userCredentials.getBytes(), Base64.DEFAULT); Base64.DEFAULT tells to use RFC2045 for base64 encoding. – Denis Gladkiy Dec 27 '13 at 10:08
  • @Denis, would you please tell me why should one use headers. I have to validate some credentials from android I am using php on xammp. how should i go for it. as i don't know how to write php code with headers – Pankaj Nimgade Feb 17 '15 at 08:00
  • 14
    Where did the variable `postData` come from in your example? – GlenPeterson Jan 11 '16 at 19:28
  • android.util.Base64 is not accessible in latest APIs, you should use org.apache.commons.codec.binary.Base64 or else you can follow this link http://androidcodemonkey.blogspot.in/2010/03/how-to-base64-encode-decode-android.html, to download Base64 class and use it. Hope it helps... – praveenb Feb 29 '16 at 14:44
  • had to replace `myURLConnection.setRequestMethod("POST");` with `myURLConnection.setRequestProperty("Request Method", "POST");` - rest worked fine! (Probably because of newer version of package?) – Samuel Jul 08 '16 at 14:54
  • 40
    Why are they called "RequestProperty" when everyone calls them Headers?? – Philip Rego Jun 21 '17 at 19:58
  • 2
    One addition for Java8 version : Base64 class is a little bit changed. Decoding should be done using: ```String basicAuth = "Basic " + java.util.Base64.getEncoder().encodeToString(userCredentials.getBytes());``` – c3R1cGFy Jan 18 '18 at 10:53
  • I don't understand how this answers the question. He said he sends the header and it doesn't arrive at the server. – Douglas Held Oct 11 '18 at 17:28
18

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);
Alex Weitz
  • 3,199
  • 4
  • 34
  • 57
Joseph Cozad
  • 190
  • 1
  • 4
14

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);
Parag Jadhav
  • 1,853
  • 2
  • 24
  • 41
Chandubabu
  • 151
  • 1
  • 6
6

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));
}
gori
  • 1,164
  • 1
  • 11
  • 14
  • 2
    @d3dave. String was created from byte array and concatenated with "Basic ". The problem in OP code was that he concatenated "Basic " with byte[] and sends it as header. – Yuriy N. Nov 16 '15 at 12:39
5

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

pintu
  • 331
  • 4
  • 7
1

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
Eyal Sooliman
  • 1,876
  • 23
  • 29
0

It work for me. I had to send request to another hand, and transfer header "Authorization" + jwt and some params via POST. By another side we formed jettyRequest with params and headers. If I send this sequence of code:

URL url = new URL(serviceURL);
HttpURLConnection myURLConnection = (HttpURLConnection)url.openConnection();
myURLConnection.setRequestMethod("POST");
myURLConnection.setRequestProperty ("Authorization", jwt); // <---- this place
// some code add params

then I received only params in a body. If I send this:

URL url = new URL(serviceURL);
HttpURLConnection myURLConnection = (HttpURLConnection)url.openConnection();
myURLConnection.setRequestProperty ("Authorization", jwt); // <---- this place
myURLConnection.setRequestMethod("POST");
// some code add params

then I received headers Authorization and params.

ivvasch
  • 1
  • 1
-1

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

Hari Krishna
  • 3,658
  • 1
  • 36
  • 57