title: Getting Twitter auth token with Volley POST request
body: <p>I'm trying to produce a proper request for Twitter Application-only authorization token using a Volley POST request, but I keep getting a Http 400 response (Bad Request). </p>
  
  <p>This is what I tried :</p>
  
  <p><strong>URL</strong></p>
  
  <pre><code>private static final String TWITTER_API_AUTH_URL = "https://api.twitter.com/oauth2/token";
  </code></pre>
  
  <p><strong>Encoding the consumer key and the consumer secret</strong></p>
  
  <pre><code>try {
      byte[] data = (URLEncoder.encode(TWITTER_CONSUMER_KEY, "UTF-8") + ":" + URLEncoder.encode(TWITTER_CONSUMER_SECRET, "UTF-8")).getBytes("UTF-8");
      mEncodedKeyAndSecret = Base64.encodeToString(data, Base64.DEFAULT);
  } catch (UnsupportedEncodingException e) {
      //handleError
  }
  </code></pre>
  
  <p><strong>Custom Volley StringRequest</strong></p>
  
  <pre><code>private class TokenRequestWithAuthHeader extends StringRequest{
  
      public TokenRequestWithAuthHeader (int method, String url, Response.Listener listener, Response.ErrorListener errorListener)
      {
          super(method, url, listener, errorListener);
      }
  
      @Override
      public Map getHeaders() throws AuthFailureError {
          Map headers = new HashMap();
          headers.put("Content-Length", String.valueOf(getBody().length));
          headers.put("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
          headers.put("Authorization", "Basic " + mEncodedKeyAndSecret);
          return headers;
      }
  
      @Override
      public byte[] getBody() {
          return ("grant_type=client_credentials").getBytes();
      }
  }
  </code></pre>
  
  <p><strong>Sending Request</strong></p>
  
  <pre><code>tokenRequest = new TokenRequestWithAuthHeader 
                  (Request.Method.POST, TWITTER_API_AUTH_URL,  mCallback.getTokenResponseListener(), mCallback);
  requestQueue.add(tokenRequest);
  </code></pre>
  
  <p><a href="https://dev.twitter.com/oauth/application-only" rel="nofollow"><strong>Documentation about Application-Only authentication at dev.twitter.com</strong></a></p>
  
  <p>I also tried extending <code>JsonObjectRequest</code> and <code>JsonRequest</code> instead of <code>StringRequest</code>, same result. </p>
  
  <p>Can someone help identify what is the problem with the request ? </p>