3

I am using HttpMethodBase in common method like submitRequest(HttpMethodBase method,String input) for PostMethod method = new PostMethod(url) or GetMethod method = new GetMethod(url)

but we just updated to HttpClient4 and there is no clear way to use the common object as it was in version 3.

Whats the best way to get some common object for Post,Get,Delete etc. I don't want to maintain the different methods for post,get or delete.

1

1 Answer 1

3

You can create a DefaultHttpClient and different methods (GET,POST) and then execute the method using the DefaultHttpClient. For example,

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;



public class MyHttp
{

    public class Constants
    {
        public final static int METHOD_GET = 1;
        public final static int METHOD_POST = 2;            
    }               

    public void executeHttpRequest(String targetUrl, int methodType) throws ClientProtocolException, IOException
    {
        HttpRequestBase method = null;
        DefaultHttpClient httpclient = new DefaultHttpClient();

        switch (methodType)
        {
            case Constants.METHOD_GET : 
                method = new HttpGet(targetUrl);
                break;
            case Constants.METHOD_POST : 
                method = new HttpPost(targetUrl);
                break;
        }

        HttpResponse response = httpclient.execute(method);
    }

}
2
  • I want to do something like HttpMethodBase method; switch (methodType) { case Constants.METHOD_GET : method = new HttpGet(targetUrl); case Constants.METHOD_GET : method = new HttpPost(targetUrl); Feb 1, 2012 at 3:14
  • Rahul Reddy, thanks, much clearer, I have edited the answer. Take a look.
    – Jasonw
    Feb 1, 2012 at 4:04

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.