Android GET and POST Request

前端 未结 6 1729
执念已碎
执念已碎 2021-02-01 11:14

Can anyone point me to a good implementation of a way to send GET and POST Requests. They are alot of ways to do these, and i am looking for the best implementation. Secondly is

6条回答
  •  感情败类
    2021-02-01 12:19

    private RequestListener listener;
    private int requestId;
    private HashMap reqParams;
    private File file;
    private String fileName;
    private RequestMethod reqMethod;
    private String url;
    private Context context;
    private boolean isProgressVisible = false;
    private MyProgressDialog progressDialog;
    
    public NetworkClient(Context context, int requestId, RequestListener listener,
                         String url, HashMap reqParams, RequestMethod reqMethod,
                         boolean isProgressVisible) {
    
        this.listener = listener;
        this.requestId = requestId;
        this.reqParams = reqParams;
        this.reqMethod = reqMethod;
        this.url = url;
        this.context = context;
        this.isProgressVisible = isProgressVisible;
    }
    
    public NetworkClient(Context context, int requestId, RequestListener listener,
                         String url, HashMap reqParams, File file, String fileName, RequestMethod reqMethod,
                         boolean isProgressVisible) {
    
        this.listener = listener;
        this.requestId = requestId;
        this.reqParams = reqParams;
        this.file = file;
        this.fileName = fileName;
        this.reqMethod = reqMethod;
        this.url = url;
        this.context = context;
        this.isProgressVisible = isProgressVisible;
    }
    
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        if (isProgressVisible) {
            showProgressDialog();
        }
    }
    
    @Override
    protected String doInBackground(Void... params) {
    
        try {
    
            if (Utils.isInternetAvailable(context)) {
    
                OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
                clientBuilder.connectTimeout(10, TimeUnit.SECONDS);
                clientBuilder.writeTimeout(10, TimeUnit.SECONDS);
                clientBuilder.readTimeout(20, TimeUnit.SECONDS);
                OkHttpClient client = clientBuilder.build();
    
                if (reqMethod == RequestMethod.GET) {
    
                    Request.Builder reqBuilder = new Request.Builder();
                    reqBuilder.url(url);
                    Request request = reqBuilder.build();
                    Response response = client.newCall(request).execute();
                    String message = response.message();
                    String res = response.body().string();
    
                    JSONObject jObj = new JSONObject();
                    jObj.put("statusCode", 1);
                    jObj.put("response", message);
                    return jObj.toString();
    
                } else if (reqMethod == RequestMethod.POST) {
    
    
                    FormBody.Builder formBuilder = new FormBody.Builder();
    
                    RequestBody body = formBuilder.build();
    
                    Request.Builder reqBuilder = new Request.Builder();
                    reqBuilder.url(url);
                    reqBuilder.post(body);
                    Request request = reqBuilder.build();
                    Response response = client.newCall(request).execute();
    
                    String res = response.body().string();
    
                    JSONObject jObj = new JSONObject();
                    jObj.put("statusCode", 1);
                    jObj.put("response", res);
                    return jObj.toString();
    
                } else if (reqMethod == RequestMethod.MULTIPART) {
    
                    MediaType MEDIA_TYPE = fileName.endsWith("png") ?
                            MediaType.parse("image/png") : MediaType.parse("image/jpeg");
    
                    MultipartBody.Builder multipartBuilder = new MultipartBody.Builder();
                    multipartBuilder.setType(MultipartBody.FORM);
    
                    multipartBuilder.addFormDataPart("file", fileName, RequestBody.create(MEDIA_TYPE, file));
    
                    RequestBody body = multipartBuilder.build();
    
                    Request.Builder reqBuilder = new Request.Builder();
                    reqBuilder.url(url);
                    reqBuilder.post(body);
                    Request request = reqBuilder.build();
                    Response response = client.newCall(request).execute();
                    String res = response.body().string();
    
    
                    JSONObject jObj = new JSONObject();
                    jObj.put("statusCode", 1);
                    jObj.put("response", res);
                    return jObj.toString();
                }
    
            } else {
    
                JSONObject jObj = new JSONObject();
                jObj.put("statusCode", 0);
                jObj.put("response", context.getString(R.string.no_internet));
                return jObj.toString();
            }
        } catch (final Exception e) {
            e.printStackTrace();
            JSONObject jObj = new JSONObject();
            try {
                jObj.put("statusCode", 0);
                jObj.put("response", e.toString());
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            return jObj.toString();
        }
    
        return null;
    }
    
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        try {
            JSONObject jObj = new JSONObject(result);
            if (jObj.getInt("statusCode") == 1) {
                listener.onSuccess(requestId, jObj.getString("response"));
            } else {
                listener.onError(requestId, jObj.getString("response"));
            }
        } catch (Exception e) {
            listener.onError(requestId, result);
        } finally {
            dismissProgressDialog();
        }
    }
    
    
    private void showProgressDialog() {
        progressDialog = new MyProgressDialog(context);
    }
    
    private void dismissProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }
    
    
    private static NetworkManager instance = null;
    private Set arrRequestListeners = null;
    private int requestId;
    public boolean isProgressVisible = false;
    
    private NetworkManager() {
        arrRequestListeners = new HashSet<>();
        arrRequestListeners = Collections.synchronizedSet(arrRequestListeners);
    }
    
    public static NetworkManager getInstance() {
        if (instance == null)
            instance = new NetworkManager();
        return instance;
    }
    
    public synchronized int addRequest(final HashMap params, Context context, RequestMethod reqMethod, String apiMethod) {
    
        try {
    
            String url = Constants.WEBSERVICE_URL + apiMethod;
            requestId = UniqueNumberUtils.getInstance().getUniqueId();
    
            NetworkClient networkClient = new NetworkClient(context, requestId, this, url, params, reqMethod, isProgressVisible);
            networkClient.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    
        } catch (Exception e) {
            onError(requestId, e.toString() + e.getMessage());
        }
    
        return requestId;
    }
    
    
    
    public synchronized int addMultipartRequest(final HashMap params, File file, String fileName, Context context, RequestMethod reqMethod, String apiMethod) {
    
        try {
    
            String url = Constants.WEBSERVICE_URL + apiMethod;
            requestId = UniqueNumberUtils.getInstance().getUniqueId();
    
            NetworkClient networkClient = new NetworkClient(context, requestId, this, url, params, file, fileName, reqMethod, isProgressVisible);
            networkClient.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    
        } catch (Exception e) {
            onError(requestId, e.toString() + e.getMessage());
        }
    
        return requestId;
    }
    
    public void isProgressBarVisible(boolean isProgressVisible) {
        this.isProgressVisible = isProgressVisible;
    }
    
    public void setListener(RequestListener listener) {
        try {
            if (listener != null && !arrRequestListeners.contains(listener)) {
                arrRequestListeners.add(listener);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    @Override
    public void onSuccess(int id, String response) {
    
        if (arrRequestListeners != null && arrRequestListeners.size() > 0) {
            for (RequestListener listener : arrRequestListeners) {
                if (listener != null)
                    listener.onSuccess(id, response);
            }
        }
    }
    
    @Override
    public void onError(int id, String message) {
        try {
            if (Looper.myLooper() == null) {
                Looper.prepare();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (arrRequestListeners != null && arrRequestListeners.size() > 0) {
            for (final RequestListener listener : arrRequestListeners) {
                if (listener != null) {
                    listener.onError(id, message);
                }
            }
        }
    }
    
    public void removeListener(RequestListener listener) {
        try {
            arrRequestListeners.remove(listener);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    Create RequestListner intreface

    public void onSuccess(int id, String response);
    
    public void onError(int id, String message);
    

    Get Unique Number

    private static UniqueNumberUtils INSTANCE = new UniqueNumberUtils();
    
    private AtomicInteger seq;
    
    private UniqueNumberUtils() {
        seq = new AtomicInteger(0);
    }
    
    public int getUniqueId() {
        return seq.incrementAndGet();
    }
    
    public static UniqueNumberUtils getInstance() {
        return INSTANCE;
    }
    

提交回复
热议问题