Android Asynchronous Http Client

Quickly share your Android Code Snippets here...

Android Asynchronous Http Client

Postby briantsim » Thu Jan 26, 2012 2:21 am

Hi all,

please suggest good async http request library. i tired http://loopj.com/android-async-http/, the library cannot set request header.

best regards,
briantsim
Freshman
Freshman
 
Posts: 7
Joined: Thu Dec 02, 2010 7:49 am

Top

Re: Android Asynchronous Http Client

Postby Phyll » Thu Feb 02, 2012 2:42 am

Hi briantsim,

Don't have too many takers on this problem huh?

Here is a piece of code to do what you want I think.

Code: Select all
package com.bandpsoftware.app5;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.util.Log;


public class Translate {
   
public String url = "";
public String referer = "";

private DefaultHttpClient httpclient;
private HttpPost httppost;
public String address = "";
public Map<String,String> vars = new HashMap<String,String>();
private ArrayList<BasicNameValuePair> pairs;   
public boolean connected;
public int curCount = 0;

public Translate(String mUrl, String mReferer) {
   url = mUrl;
   referer = mReferer;
}

public String execute(String text, String from, String to) {

    String strUrl = url;
    if (!strUrl.startsWith("http://")) strUrl = "http://" + strUrl;
   String returnString = "";

   vars.clear();
    vars.put("hl","en");
    vars.put("ie", "UTF8");
    vars.put("oe", "UTF8");
    vars.put("submit","Translate");
    vars.put("langpair",from+"|"+to);                  //another User-Agent "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)"
    vars.put("text", text);                            //another Accept text/plain
    HttpParams(strUrl, vars);
     
    httppost.setHeader("Method", "POST");
    httppost.setHeader("Accept", "application/json");                                         
    httppost.setHeader("User-Agent", "Apache-HttpClient/4.1 (java 1.5)");                           
    httppost.setHeader("Referer", referer);
    httppost.setHeader("Auto-Redirect", "true");                                              //Don't know about this
    httppost.setHeader("Time-Out", "5000");                                                   //Don't know about this
    httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");   
    //httppost.setHeader("Authorization",getB64Auth());                                       //Might need some time
    try {
   UrlEncodedFormEntity ent = new UrlEncodedFormEntity(pairs, "ISO-8859-1");
    httppost.setEntity(ent);
    httppost.setURI(new URI(strUrl));
    HttpResponse response =httpclient.execute(httppost);     
    HttpEntity entity = response.getEntity();
    InputStream contents = entity.getContent();
    returnString = convertStreamToString(contents);
    int status_code = response.getStatusLine().getStatusCode();
    Log.e("POST","Status code = "+status_code);
   
    } catch (UnsupportedEncodingException uee) {
       Log.e("POST","Encoding Error");
       uee.printStackTrace();
    } catch (IOException ioe) {
       Log.e("POST","IOException");
       ioe.printStackTrace();
    } catch(IllegalStateException ise) {
       Log.e("POST","State Error");
       ise.printStackTrace();
        }//catches
catch (URISyntaxException e) {
       Log.e("POST","State Error");
       e.printStackTrace();
      e.printStackTrace();
   }
    return returnString;
}

private String convertStreamToString(InputStream is) {
   BufferedReader reader = new BufferedReader(new InputStreamReader(is));
   StringBuilder sb = new StringBuilder();
   String line = null;
   try {
      while ((line = reader.readLine()) != null) {
         sb.append(line + "\n");
         }
       } catch (IOException e) {
          e.printStackTrace();
       } finally {
   try {
      is.close();
      } catch (IOException e) {
         e.printStackTrace();
          }//catch
       }//finally
   return sb.toString();
    }//convertstreamtostring

private void HttpParams(String url, Map<String,String> variables) {
   httpclient = new DefaultHttpClient();
   httppost = new HttpPost(url);
   pairs = new ArrayList<BasicNameValuePair>();
   if(variables != null){
      Set<String> keys = variables.keySet();
      for(Iterator<String> i = keys.iterator(); i.hasNext();) {
         String key = (String)i.next();
         pairs.add(new BasicNameValuePair(key, variables.get(key)));
          }
       }
    }//httpparams

}//class


It's just a chunk of code out of a working app so it may have more than you need or not enough but I think it is what you are after.

Let me know how you make out.

Phyll
Phyll
Master Developer
Master Developer
 
Posts: 648
Joined: Fri Oct 14, 2011 11:19 am

Top

Return to Code Snippets for Android

Who is online

Users browsing this forum: No registered users and 2 guests