6

WHy am I get this error : java.lang.IllegalArgumentException: This consumer expects requests of type org.apache.http.HttpRequest

CommonsHttpOAuthConsumer  consumer = new CommonsHttpOAuthConsumer (CONSUMER_KEY,CONSUMER_SECRET);
            consumer.setTokenWithSecret(oaut_token, tokenSecret);

URL url = new URL(targetURL);
request = (HttpURLConnection) url.openConnection();

// sign the request
consumer.sign(request);
// send the request
request.connect();

EDIT: Just updating the accepted answer as it is not relevant anymore. the signpost documentation is a bit outdated and suggest to use CommonsHttpOAuthConsumer in Android due to bugs on HttpURLConnection. These have been fixed and now Android removed the Apache HTTP so the correct way to deal with signpost is now via DefaultOAuthConsumer.

DefaultOAuthConsumer  consumer = new DefaultOAuthConsumer (CONSUMER_KEY,CONSUMER_SECRET);
            consumer.setTokenWithSecret(oaut_token, tokenSecret);

URL url = new URL(targetURL);
request = (HttpURLConnection) url.openConnection();

// sign the request

consumer.sign(request);
1
  • Take a look at the answer I provided (couple down) ran into same problem, the outlined solution worked for me.
    – Idistic
    Apr 13, 2012 at 22:09

4 Answers 4

5

Signpost is trivial to use on android, lol, once you get past the tutorials that are not really up to date, or complete, or in particularly useful order.

Anyway here is one way to do this using apache http instead of native android, it's a bit ugly for the sake of brevity but should get you up and running.

Modifed your code a bit to make it work, you probably want to make the HttpClient consistent across calls but I just inlined all that. I also notice you are deserializing the tokens so I am just going to assume that you have the actual OAuth flow working.

Good luck!

    CommonsHttpOAuthConsumer consumer = null;
    consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY,CONSUMER_SECRET);
    consumer.setTokenWithSecret(oaut_token, tokenSecret);

   // Use the apache method instead - probably should make this part persistent until
   // you are done issuing API calls    
   HttpParams parameters = new BasicHttpParams();
   HttpProtocolParams.setVersion(parameters, HttpVersion.HTTP_1_1);
   HttpProtocolParams.setContentCharset(parameters, HTTP.DEFAULT_CONTENT_CHARSET);
   HttpProtocolParams.setUseExpectContinue(parameters, false);
   HttpConnectionParams.setTcpNoDelay(parameters, true);
   HttpConnectionParams.setSocketBufferSize(parameters, 8192);

   HttpClient httpClient = new DefaultHttpClient();

   SchemeRegistry schReg = new SchemeRegistry();
   schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
   ClientConnectionManager tsccm = new ThreadSafeClientConnManager(parameters, schReg);

   httpClient = new DefaultHttpClient(tsccm, parameters);

   HttpGet get = new HttpGet(targetURL); 

    // sign the request
    consumer.sign(get);

    // send the request & get the response (probably a json object, but whatever)
    String response = httpClient.execute(get, new BasicResponseHandler());

    // shutdown the connection manager - last bit of the apache code 
    httpClient.getConnectionManager().shutdown();

    //Do whatever you want with the returned info 
    JSONObject jsonObject = new JSONObject(response);

That's it

3
  • Is there a built in signpost method to generate signatures?
    – Fabii
    Apr 14, 2012 at 1:03
  • @Fabii not sure I understand exactly what you are asking, the sign method takes care of pretty much everything for you, or are you looking for a semi-automated helper method to construct a signature yourself so that you can modify? (Things like the nonce, tokens, etc)
    – Idistic
    Apr 17, 2012 at 6:10
  • I wonder how is this done with HTTPUrlConnection now that HttpClient is deprecated in android
    – Josh
    Oct 17, 2020 at 9:37
5

It should be obvious in the code you posted that request is not of type HttpRequest...

request = (HttpURLConnection) url.openConnection();
consumer.sign(request);
4
  • So you're saying that this site is inccorrect ? :code.google.com/p/oauth-signpost/wiki/GettingStarted
    – Fabii
    Apr 13, 2012 at 17:47
  • Are you using Apache Commons HTTP? Are you writing this for Android? There are a lot of caveats in that article. This might be relevant: If you need to sign requests for other HTTP request types, please have a look at the examples in SupportedHttpLibraries Apr 13, 2012 at 18:22
  • @Fabii - Yes the tutorials there don't show the use of Apache Http, which is required for Android apps because of a bug in the android handlers. Travis pointed you in the right direction. Take a look at my answer below for something that works with android and Signpost
    – Idistic
    Apr 13, 2012 at 22:13
  • @Idistic your answer is above now |o|
    – Gem
    Aug 25, 2015 at 12:09
1

The exception java.lang.IllegalArgumentException is thrown when the method is expecting an argument type and it recieves of another type.
In this case the method is sign and the argument is request:

consumer.sign(request); 

Where it's waiting to recieve HTTPRequest type and it's recieving another type.

0
public class BlockTicketPostOauth extends AsyncTask<String, Void, Integer> {
    ProgressDialog pd;
    String response;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd=new ProgressDialog(BusPassengerInfo.this);
        pd.setMessage("wait continue to payment....");
        pd.show();

    }

    @Override
    protected Integer doInBackground(String... params) {
        InputStream inputStream = null;
        String ul ="http://api.seatseller.travel/blockTicket";

        String  JSONPayload=params[0];
        Integer result = 0;
        try {

            OAuthConsumer consumer = new CommonsHttpOAuthConsumer(YOUR CONSUMER KEY,YOUR CONSSUMER SECRETE); consumer.setTokenWithSecret(null, null);

            /* create Apache HttpClient */
            HttpClient httpclient = new DefaultHttpClient();

            /* Httppost Method */
            HttpPost httppost = new HttpPost(ul);

            // sign the request
            consumer.sign(httppost);

            // send json string to the server
            StringEntity paras =new StringEntity(JSONPayload);

            //seting the type of input data type
            paras.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

            httppost.setEntity(paras);

            HttpResponse httpResponse= httpclient.execute(httppost);

            int statusCode = httpResponse.getStatusLine().getStatusCode();

            Log.i("response json:","status code is:"+statusCode);
            Log.i("response json:","status message?:"+httpResponse.getStatusLine().toString());

            /* 200 represents HTTP OK */
            if (statusCode ==  200) {
                /* receive response as inputStream */
                inputStream = httpResponse.getEntity().getContent();
                response = convertInputStreamToString(inputStream);

                Log.i("response json:","json response?:"+response);

                Log.i("response block ticket :","status block key:"+response);

                result = 1; // Successful
            } else{
                result = 0; //"Failed to fetch data!";
            }
        } catch (Exception e) {
            Log.d("response error", e.getLocalizedMessage());
        }
        return result; //"Failed to fetch data!";
    }

    @Override
    protected void onPostExecute(Integer result) {

        if(pd.isShowing()){
            pd.dismiss();
        }
        /* Download complete. Lets update UI */
        if(result == 1){

            Toast.makeText(BusPassengerInfo.this,"response is reult suceess:"+response,Toast.LENGTH_SHORT).show();

//allowing the customer to going to the payment gate way

        }else{
            Log.e("response", "Failed to fetch data!");
            Toast.makeText(BusPassengerInfo.this,"response is reult fail",Toast.LENGTH_SHORT).show();
        }

    }
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.