Android project using httpclient –> http.client (apache), post/get method

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 its 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);
         }
      }
   }

Leave a Comment