Okhttp


Lib

implementation 'com.squareup.okhttp3:okhttp:3.12.1'


implementation 'com.google.code.gson:gson:2.8.2'

Gson gson = GsonUtils.getInstance().getGson(GsonUtils.TYPE_WITHOUT_EXPOSE);
ArtistDetail artistdetail = gson.fromJson(detailresponse, ArtistDetail.class);

CommunicationManager.java

mport android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.internal.http2.Header;

public class CommunicationManager {

    public void callapi(Httpcall httpcall){
//        new callokhttpt().execute(httpcall);        callmethod(httpcall);
    }

    static CommunicationManager communicationManager;
    static callback callbacks;
    static String GET="get";
    static String POST="post";
    static Context context;
    public static CommunicationManager getInstance(Context mContext,callback mCallback){
        if(communicationManager==null) {
            communicationManager = new CommunicationManager();
            callbacks = mCallback;
            context=mContext;
        }
        return communicationManager;
    }


    private void  callmethod(Httpcall httpcall){
        try {
           // Httpcall httpcall=httpcalls[0];            OkHttpClient client = new OkHttpClient();
            String url=httpcall.getUrl();
            Request request;
            Log.i("ApiCall:::","Okhttp::Start");
            if(httpcall.getMethod().equals(GET)){
                request = new Request.Builder()
                        .get()
                        .url(url)
                        .build();
            }else {
                MediaType MEDIA_TYPE = MediaType.parse("application/json");
                JSONObject postdata = new JSONObject();
                if(httpcall.getParams()!=null && httpcall.getParams().size()>0) {
                    for (String key : httpcall.getParams().keySet()) {
                        postdata.put(key, httpcall.getParams().get(key));
                    }
                }
//                       Headers.Builder header =new Headers.Builder();//                       if(httpcall.getHeaders()!=null && httpcall.getHeaders().size()>0) {//                           for (String key : httpcall.getHeaders().keySet()) {//                               postdata.put(key, httpcall.getHeaders().get(key));//                               header.add("key",httpcall.getHeaders().get(key))//                           }//                       }
                RequestBody body = RequestBody.create(MEDIA_TYPE,
                        postdata.toString());
                request = new Request.Builder()
                        .post(body)
                        .url(url)
                        .build();

            }

            client.newCall(request).enqueue(new Callback() {
                @Override                public void onFailure(Call call, IOException e) {
                    ((Activity)context).runOnUiThread(new Runnable() {
                        @Override                        public void run() {
                            callbacks.onFail();
                        }
                    });

                }

                @Override                public void onResponse(Call call, Response response) throws IOException {
                    ((Activity)context).runOnUiThread(new Runnable() {
                        @Override                        public void run() {
                            try {
                                callbacks.onSuccess(response.body().string());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });

                }
            });


        }catch (Exception e){
            Log.i("ApiCall:::","Okhttp:::Exception");

        }
    }


    private class callokhttpt  extends AsyncTask<Httpcall,Void,String> {

        @Override        protected String doInBackground(Httpcall... httpcalls) {
            try {

                    Httpcall httpcall=httpcalls[0];
                    OkHttpClient client = new OkHttpClient();
                    String url=httpcall.getUrl();
                    Request request;
                Log.i("ApiCall:::","Okhttp::Start");
                   if(httpcall.getMethod().equals(GET)){
                         request = new Request.Builder()
                                .get()
                                .url(url)
                                .build();
                    }else {
                      MediaType MEDIA_TYPE = MediaType.parse("application/json");
                        JSONObject postdata = new JSONObject();
                        if(httpcall.getParams()!=null && httpcall.getParams().size()>0) {
                            for (String key : httpcall.getParams().keySet()) {
                                postdata.put(key, httpcall.getParams().get(key));
                            }
                        }
//                       Headers.Builder header =new Headers.Builder();//                       if(httpcall.getHeaders()!=null && httpcall.getHeaders().size()>0) {//                           for (String key : httpcall.getHeaders().keySet()) {//                               postdata.put(key, httpcall.getHeaders().get(key));//                               header.add("key",httpcall.getHeaders().get(key))//                           }//                       }
                     RequestBody body = RequestBody.create(MEDIA_TYPE,
                            postdata.toString());
                         request = new Request.Builder()
                                .post(body)
                                .url(url)
                                .build();

                    }

                    client.newCall(request).enqueue(new Callback() {
                        @Override                        public void onFailure(Call call, IOException e) {
                            ((Activity)context).runOnUiThread(new Runnable() {
                                @Override                                public void run() {
                                    callbacks.onFail();
                                }
                            });
                        }

                        @Override                        public void onResponse(Call call, Response response) throws IOException {
                            ((Activity)context).runOnUiThread(new Runnable() {
                                @Override                                public void run() {
                                    try {
                                        callbacks.onSuccess(response.body().string());
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                        }
                    });


                }catch (Exception e){
                    Log.i("ApiCall:::","Okhttp:::Exception");

                }
                return null;

        }
    }
}


ApiManager.Java

import android.content.Context;

public class ApiManager {

    static ApiManager callApi;
    static CommunicationManager communicationManager;
    public static ApiManager getInstance(Context context,callback callback){
        if(callApi==null) {
            callApi = new ApiManager();
            communicationManager=communicationManager.getInstance(context,callback);
         }
        return callApi;
    }

    public void getLocation(){
        Httpcall httpcall =new Httpcall("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=21.1586176,72.7967252&key=AIzaSyDhemrzN1Bk4XEGNvDyZFMv4UZaphl0xRA&radius=10000",
                CommunicationManager.GET,null,null);
        communicationManager.callapi(httpcall);
    }
}


MainActivity.Java

import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;



public class MainActivity extends AppCompatActivity implements ApiCallback{

   
   
    ApiManager apiManager;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        apiManager =ApiManager.getInstance(this,this);
        apiManager.getLocation();
@Override public void onSuccess(String response) { Log.i("ApiCall:::","Okhttp::Response"); } @Override public void onFail() { Log.i("ApiCall:::","Okhttp::Fail"); } }


ApiCallback.java

public interface ApiCallback {
    void onSuccess(String response,Integer code);
    void onFail();
}

Httpcall.java

private String url;
private String method;
private HashMap<String,String> params;
private HashMap<String,String> headers;
private Integer apicode;


public Httpcall(String url, String method, HashMap<String, String> params, HashMap<String, String> headers,Integer apicode) {
    this.url = url;
    this.method = method;
    this.params = params;
    this.headers = headers;
    this.apicode=apicode;
}

public String getUrl() {
    //https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=21.1586176,72.7967252&key=AIzaSyDhemrzN1Bk4XEGNvDyZFMv4UZaphl0xRA&radius=10000    return url;
}

public String getMethod() {
    return method;
}

public HashMap<String, String> getParams() {
    return params;
}

public HashMap<String, String> getHeaders() {
    return headers;
}

public Integer getApicode() {
    return apicode;
}





No comments:

Post a Comment