Rest Api call AsyncTask with HttpUrlConnection - Chapter 8

If you don't know about AsycTask then visit What is AsyncTask and How to use it?

 I am posting a code for creating http connection . This code will provide you server response in string format . You can use it as your  requirements (JSON, XML). 
You  dont need to check internet connection all the time . It will generate errors if connection lost or any miss happens. 



1: Make my first project from my previous post and add some new lines in it to get data from http: api's.

public class Example extends Activity {
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_example);
        List params = new ArrayList();
        params.add(new BasicNameValuePair("userId", "1"));

        ServerConnection task = new ServerConnection(this, new ResultListener() {
            @Override            public void result(String response) {

                Toast.make(this, response, Toast.LENGTH_LONG).show();

            }

            @Override            public void loader(boolean visble) {


            }

            @Override            public void connectionLost(String error) {
                Toast.make(this, error, Toast.LENGTH_LONG).show();
            }
        });

        task.setUrl("https://jsonplaceholder.typicode.com/posts");


    }

  Note: This will give you two error after importing all class . So we need to create some  classes to remove these errors.

2: As we know that after 2.1 android version we can't connect http: connection in android thread .Means android program runs on single thread so it won't allow you to connect with server .
To come out this situation we have to use AsycTask Class ,provided by android framework . There are other threads available in framework, but for now we use AsycTask.

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;

import database.utility.Constant;

import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;

public class ServerConnection extends AsyncTask<String, String, String> implements Constant {
    ResultListener listener;

    private String URL = "";

    private String Method = "GET";
    private List<NameValuePair> params = new ArrayList<NameValuePair>();


    private Context context;
    private ConnectionDetector cd;

    // public static Drawable drawable;    public ServerConnection(Context context, ResultListener r) {
        this.context = context;
        this.listener = r;
        cd = new ConnectionDetector(context);
        this.execute();
    }


    public boolean isConnection() {

        return cd.isConnectingToInternet();

    }

    @Override    protected void onPreExecute() {
        super.onPreExecute();

    }

    @Override    protected String doInBackground(String... arg0) {
        if (!isConnection()) {
            cancel(true);
            return "Sorry!connection lost,try again or later";
        }
        ApiResponse air = new ApiResponse();
        System.out.println("working hre" + "hi");
        String json = null;

        try {
            json = air.makeHttpRequest(URL, getMethod(), getParams());
        } catch (Exception e) {
            json = e.getMessage();
            cancel(true);
            return json;
        }


        return json;
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override    protected void onCancelled(String result) {
        listener.connectionLost(result);
        rl.connectionLost("Sorry!connection lost,try again or later");
        super.onCancelled(result);
    }

    @Override    protected void onPostExecute(String result) {
        System.out.println("onpost" + result);
        listener.result(result);
        listener.loader(true);
        super.onPostExecute(result);

    }

    public String getMethod() {
        return Method;
    }

    public void setMethod(String method) {
        Method = method;
    }

    public void setUrl(String url) {
        URL = url;
    }

    public List<NameValuePair> getParams() {
        return params;
    }

    public void setParams(List<NameValuePair> params) {
        this.params = params;
    }
}

3: Create a class which will provide you http: connected data .

public class ApiResponse {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor    public ApiResponse() {
    }

    // function get    // json from    // url    // by making    //  HTTP POST    //  or GET    //  mehtod
    public String makeHttpRequest(String url, String method, List<NameValuePair> params) throws Exception {
        HttpResponse httpResponse = null;
        //Making HTTP request            try {        //check for request method                     if (method.equalsIgnoreCase("POST")) {        //request method is POST                // defaultHttpClient                         HttpParams par = new BasicHttpParams();        par.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        DefaultHttpClient httpClient = new DefaultHttpClient(par);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        httpResponse = httpClient.execute(httpPost);
    } else if(method.equalsIgnoreCase("GET")){
// request method is GET                      HttpParams par = new BasicHttpParams();        par.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1);
        DefaultHttpClient httpClient=new DefaultHttpClient(par);
        String paramString=URLEncodedUtils.format(params,"utf-8");
        url+="?"+paramString;
        HttpGet httpGet=new HttpGet(url);
        httpResponse=httpClient.execute(httpGet);
    }
    StatusLine status=httpResponse.getStatusLine();
        if(status.getStatusCode()==HttpStatus.SC_OK){
        HttpEntity httpEntity=httpResponse.getEntity();
        is=httpEntity.getContent();
        BufferedReader reader=new BufferedReader(new InputStreamReader(
                is,"iso-8859-1"));
        StringBuilder sb=new StringBuilder();
        String line=null;
        while((line=reader.readLine())!=null){
            sb.append(line+"\n");
        }
        is.close();
        json=sb.toString();
        if(json.contains("{")){
            return json;
        }else if(json.contains("[")){
            return json;
        }else throw new Exception(json);
    }else{
        return"";
    }

}catch(UnsupportedEncodingException e){
        throw new Exception(e);
        }catch(ClientProtocolException e){
        throw new Exception(e);
        }catch(IOException e){
        throw new Exception(e);
        }

        }
        }

4: ResultListener is interface which will be use here to passing data between to class.

public interface ResultListener
{
    /*     * Server response     */    abstract void result(String list);
    /*     * Server response cancelled     */    abstract void connectionLost(String list);
    /*     * loader visibility     * when server connection     */    abstract void loader(boolean visble);

}

5: To check internet connection we need to write one more class.

public class ConnectionDetector {

    private Context _context;

    public ConnectionDetector(Context context){
        this._context = context;
    }

    /**     * Checking for all possible internet providers     * **/    public boolean isConnectingToInternet(){
        ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null)
        {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED)
                    {
                        return true;
                    }

        }
        return false;
    }

}


If you find this useful then please share and comment here

Previous
Next Post »