views:

17279

answers:

4

Hi all, I'm doing a Get and Post method for an android project and I need to "translate" HttpClient 3.x to HttpClient 4.x (using by android). My problem is that I'm not sure of what I have done and I don't find the "translation" of some methods...

This is the HttpClient 3.x I have done and (-->) the HttpClient 4.x "translation" if I have found it (Only parties who ask me problems) :

HttpState state = new HttpState (); --> ?

HttpMethod method = null; --> HttpUriRequest httpUri = null;

method.abort(); --> httpUri.abort(); //httpUri is a HttpUriRequest

method.releaseConnection(); --> conn.disconnect(); //conn is a HttpURLConnection

state.clearCookies(); --> cookieStore.clear(); //cookieStore is a BasicCookieStore

HttpClient client = new HttpClient(); --> DefaultHttpClient client = new DefaultHttpClient();

client.getHttpConnectionManager().getParams().setConnectionTimeout(SOCKET_TIMEOUT) --> HttpConnectionParams.setConnectionTimeout(param, SOCKET_TIMEOUT);

client.setState(state); --> ?

client.getParams().setCookiePolicy(CookiePolicy.RFC_2109); --> HttpClientParams.setCookiePolicy(param, CookiePolicy.RFC_2109);

PostMethod post = (PostMethod) method; --> ?

post.setRequestHeader(...,...); --> conn.setRequestProperty(...,...);

post.setFollowRedirects(false); --> conn.setFollowRedirects(false);

RequestEntity tmp = null; --> ?

tmp = new StringRequestEntity(...,...,...); --> ?

int statusCode = client.executeMethod(post); --> ?

String ret = method.getResponsBodyAsString(); --> ?

Header locationHeader = method.getResponseHeader(...); --> ?

ret = getPage(...,...); --> ?

I don't know if that is correct. This has caused problems because the packages are not named similarly, and some methods too. I just need documentation (I haven't found) and little help.

Thank you in advance for your help. Michaël

+2  A: 

Well, you can find documentation on that version of HTTPClient here; it's especially useful to go through the example scenarios they present.

I unfortunately don't know version 3 of HTTPClient so I can't give direct equivalences; I suggest you take what you're trying to do and look through their example scenarios.

Daniel Martin
Thank you,I will look at the documentation and I hope to find the solution of my problem.
Michaël
+3  A: 

The easiest way to answer my question is to show you the class that I made :

public class HTTPHelp{

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    private boolean abort;
    private String ret;

    HttpResponse response = null;
    HttpPost httpPost = null;

    public HTTPHelp(){

    }

    public void clearCookies() {

     httpClient.getCookieStore().clear();

    }

    public void abort() {

     try {
      if(httpClient!=null){
       System.out.println("Abort.");
       httpPost.abort();
       abort = true;
      }
     } catch (Exception e) {
      System.out.println("HTTPHelp : Abort Exception : "+e);
     }
    }

    public String postPage(String url, String data, boolean returnAddr) {

     ret = null;

     httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);

     httpPost = new HttpPost(url);
     response = null;

     StringEntity tmp = null;  

     httpPost.setHeader("User-Agent", "Mozilla/5.0 (X11; U; Linux " +
      "i686; en-US; rv:1.8.1.6) Gecko/20061201 Firefox/2.0.0.6 (Ubuntu-feisty)");
     httpPost.setHeader("Accept", "text/html,application/xml," +
      "application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
     httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

     try {
      tmp = new StringEntity(data,"UTF-8");
     } catch (UnsupportedEncodingException e) {
      System.out.println("HTTPHelp : UnsupportedEncodingException : "+e);
     }

     httpPost.setEntity(tmp);

     try {
      response = httpClient.execute(httpPost,localContext);
     } catch (ClientProtocolException e) {
      System.out.println("HTTPHelp : ClientProtocolException : "+e);
     } catch (IOException e) {
      System.out.println("HTTPHelp : IOException : "+e);
     } 
                ret = response.getStatusLine().toString();

                return ret;
                }
}

I used this tutorial to do my post method : http://wiki.apache.org/HttpComponents/HttpClientTutorial and thoses examples : http://hc.apache.org/httpcomponents-client/examples.html (Thanks Daniel) Thank your for your help.

Michaël
+6  A: 

Here are the HttpClient 4 docs, that is what Android is using (4, not 3, as of 1.0->2.x). The docs are hard to find (thanks Apache ;)) because HttpClient is now part of HttpComponents (and if you just look for HttpClient you will normally end up at the 3.x stuff).

Also, if you do any number of requests you do not want to create the client over and over again. Rather, as the tutorials for HttpClient note, create the client once and keep it around. From there use the ThreadSafeConnectionManager.

I use a helper class, for example something like HttpHelper (which is still a moving target - I plan to move this to it's own Android util project at some point, and support binary data, haven't gotten there yet), to help with this. The helper class creates the client, and has convenience wrapper methods for get/post/etc. Anywhere you USE this class from an Activity, you should create an internal inner AsyncTask (so that you do not block the UI Thread while making the request), for example:

    private class GetBookDataTask extends AsyncTask<String, Void, Void> {
      private ProgressDialog dialog = new ProgressDialog(BookScanResult.this);

      private String response;
      private HttpHelper httpHelper = new HttpHelper();

      // can use UI thread here
      protected void onPreExecute() {
         dialog.setMessage("Retrieving HTTP data..");
         dialog.show();
      }

      // automatically done on worker thread (separate from UI thread)
      protected Void doInBackground(String... urls) {
         response = httpHelper.performGet(urls[0]);
         // use the response here if need be, parse XML or JSON, etc
         return null;
      }

      // can use UI thread here
      protected void onPostExecute(Void unused) {
         dialog.dismiss();
         if (response != null) {
            // use the response back on the UI thread here
            outputTextView.setText(response);
         }
      }
   }
Charlie Collins
Even better than my HttpHelper is the one the ZXing project uses - http://code.google.com/p/zxing/source/browse/trunk/android/src/com/google/zxing/client/android/AndroidHttpClient.java. A little more difficult to work with (though still pretty easy), and more capable. (And I noticed it AFTER I had been using the one I wrote for a long time, similar approach, though not identical, but convergent, not copied. ;).)
Charlie Collins
The HTTP client docs have moved — now at: http://hc.apache.org/httpcomponents-client-ga/index.html
ohhorob
A: 

I had a similar problem with the Post Method parameters when switching form 3 to 4. This might help you.

php html