5

So I am currently writing an android app that will get tweets from a particular user, using Twitter's 1.1 Application-only-auth, which requires a POST HTTP request to get a bearer token. I have a method set up that uses an HttpsURLConnection to open a connection, but

  • conn.setDoOutput(true); method isn't working
  • conn.doOutput stays false
  • the request stays the default GET.

Am I doing something wrong?

This method is called in an AsyncTask's doInBackground() method:

public String getRequestBearerToken(String endUrl) throws IOException {
    String encodedCred = encodeKeys("API-key", "API-secret");
    HttpsURLConnection connection = null;
    try {
        URL url = new URL(endUrl);
        connection = (HttpsURLConnection) url.openConnection();

        connection.setInstanceFollowRedirects(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        connection.setRequestMethod("POST");


            // POST request properties
            connection.setRequestProperty("Host", "api.twitter.com");
            connection.setRequestProperty("User-Agent", getResources()
                    .getString(R.string.app_name));
            connection.setRequestProperty("Authorization", "Basic "
                    + encodedCred);
            connection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded;charset=UTF-8");
            connection.setRequestProperty("Content-Length", "29");
            connection.setUseCaches(false);

            ...
sarangj
  • 300
  • 2
  • 10
  • Use volley library for REST API's its very easy and time efficient. http://www.itsalif.info/content/android-volley-tutorial-http-get-post-put – cesztoszule Mar 24 '14 at 09:56
  • I'm using the Volley library for POST requests. I know how to set the params, but how do I set the main request body? – sarangj Mar 25 '14 at 03:32
  • just put the request in a method and call it when you have to, and in your Activity/class make a variable RequestQueue queue. and in oncreate or in a classc constructore, set it like this requestQueue = Volley.newRequestQueue(ctx); (this is what you meant by main request right) ? – cesztoszule Mar 25 '14 at 13:21
  • That is also helpful, but I was wondering where to set the body of the HTTP request. This is separate from the headers. – sarangj Mar 26 '14 at 02:58
  • Yeah for some reason the Volley library isn't working out for me. Anyone have any idea about the original problem? – sarangj Mar 30 '14 at 05:17

0 Answers0