Search code examples
javaandroidtwitter-oauth

Getting content from http request android, conent ill-formed


I am trying to connect to the twitter API using OAuth2 method toget the bearer token. I am using an AsyncTask making the call to Twitter. My request seems to be accepted and return an error code 200, but when I try to read the content which is supposed to contain the token that I want, but the format is odd, as well as the content-length of the response.

I am building it according to this link.

Here is the AsyncTask I am using to make the request:

private class RequestBearerTockenTask extends AsyncTask<String, Integer, String> {
    @Override
    protected String doInBackground(String... string) {

        // On récupère les keys passées en paramètre
        String consumerKey = string[0];
        String secretKey = string[1];

        // On encode en base64 le bearerToken en accord avec la doc twitter
        String base64encodedBearerToken = Base64.encodeToString((consumerKey + ":" + secretKey).getBytes(), Base64.NO_WRAP);

        // Variables locales de la fonction
        String bearerTocken = "";
        URL url = null;
        HttpURLConnection urlConnection = null;

        try {
            // On formate la requete HTTP
            url = new URL("https://api.twitter.com/oauth2/token");
            urlConnection = (HttpURLConnection) url.openConnection();

            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("Host", "api.twitter.com");
            urlConnection.setRequestProperty("User-Agent", " My Twitter App v1.0.23");
            urlConnection.setRequestProperty("Authorization", "Basic " + base64encodedBearerToken);
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            urlConnection.setRequestProperty("Content-Length", "29");
            urlConnection.setRequestProperty("Accept-Encoding", "gzip");

            String requestBody =  "grant_type=client_credentials";
            byte[] outputInBytes = requestBody.getBytes("UTF-8");
            OutputStream os = urlConnection.getOutputStream();
            os.write( outputInBytes );
            os.close();

            // On lit l'entete de la reponse
            int responseCode = urlConnection.getResponseCode();

            switch (responseCode) {
                case 200:
                case 201:

                    BufferedReader rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                    String line;
                    while ((line = rd.readLine()) != null) {
                        bearerTocken += line;
                    }
                    break;
                default:
                    bearerTocken = "";
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bearerTocken;
    }
}

The bearerToken at the end is like:

����������������V*��N͋/�,HU�RJJM,J-R�QJLNN-.�K�����/�rW03��5��+81��$���=?[��)�ɱ���B�إа�2�)+����$�2�� ����?���?7�;�0�2�995=�-=/$$�"�30T�����������9�뇛������

with a content length of 149 instead of 140 according to the documentation.

Do you have any clue why I am getting such a response?


Solution

  • If you are not decoding/handling the gzip compression, why you are using it? the content is encoded in gzip. Before using it, you need to decode it. I suggest you not to use that encoding while calling the API. remove the code line urlConnection.setRequestProperty("Accept-Encoding", "gzip"); and all should work.