316

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);
        }
4
  • Works for me, how do you tell the header was sent and not received? Commented Oct 4, 2012 at 17:26
  • 3
    sorry if this sounds dumb, but where are you calling connect() on the URLConnection? Commented Oct 4, 2012 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)? Commented Oct 4, 2012 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. Commented Apr 12, 2019 at 12:07

8 Answers 8

516

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

Sign up to request clarification or add additional context in comments.

8 Comments

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, 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
Where did the variable postData come from in your example?
Why are they called "RequestProperty" when everyone calls them Headers??
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());
|
20

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

Comments

15

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

Comments

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

1 Comment

@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.
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

Comments

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

2 Comments

Do you mind formatting the code here a bit more cleanly? Also, what is given() supposed to be?
Hi, This is the base usage for rest-Assurd (testing rest Api). I added explains to the code.
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.

Comments

0

if you are sure that the server is trustworthy and you are only connecting to it for testing purposes, you can use this option.

You will need to modify your Java code to use a custom TrustManager that does not validate the server's certificate.

additional code snippet for json body. And also send request and get repsponse examples:

//Create json body 
// option1
            JSONObject json = new JSONObject();
            json.put("param1Name", param1);
            json.put("param2Name", param2); 

//Create json body 
// option2
//String jsonInputString = "{"param1Name": param1, "param2Name": param2}";

            String jsonInputString = json.toJSONString();
//Create the Request Body
            try(OutputStream os = myURLConnection.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

//Read the Response From Input Stream
            try(BufferedReader br = new BufferedReader(
                    new InputStreamReader(myURLConnection.getInputStream(), "utf-8"))) {

                String responseLine = null;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                System.out.println(response.toString());

            }

Here is an full example of such a code is here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.