Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending authorization headers using httpUrlConnection in Android

Tags:

java

android

I am trying to set "Authorization" header while using HttpUrlConnection but I see it on the server as "HTTP_AUTHORIZATION".

Here is my code:

public static String doGet(String params, String accessToken)
            throws MHNetworkException {
        try {
            URL url = new URL(getServerUrl());

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Authorization", "Token token="
                    + accessToken);
            conn.setRequestMethod("GET");

            int httpStatus = conn.getResponseCode();
            Log.v(tag, "httpStatus " + httpStatus);

            if (httpStatus == 200) {
                return MHIOUtil.getInputStreamAsString(conn.getInputStream());
            } 
        } catch (MalformedURLException me) {

        } catch (IOException ioe) {

        }
    }

BTW the "Content-Type" header is also being changed to CONTENT_TYPE.

Why is Android sending changing it and is there any way for me to sent it exactly in the way I want. Or am I doing something wrong here? We are using nginx and Rails on the backend if that matters.

Please do not recommend using HttpClient. I just want to use HttpURLConnection if I can get this to work as Google's Android Developers said that they are going to put all their efforts in HttpURLConnection.

Thank you.

like image 951
achie Avatar asked Apr 28 '26 23:04

achie


1 Answers

There is nothing wrong. Most of the headers will be accessible on the server prefixed with HTTP_ but Content-Type is treated specially. Android is not changing it, the mapping is happening on the server. The mapping to upper case is standard (case of headers is not significant) as is the replacement of"-" by "_".

See the CGI specification.

like image 98
Clyde Avatar answered May 01 '26 13:05

Clyde