實現自己的網絡請求工具(一)

實現自己的網絡請求工具(一)

直接上代碼:

package com.example.Util;

import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;


public class NetWork {
    private static final String TAG = "NetWork";

    public enum Method{
        GET,POST
    }

    public interface OnCallBack<T> {
        int ERROR = -1;

        NetworkInfo getNetWorkInfo();

        void onResuLtOnCallBack(T result);

        Map<String,String> getParmas();
    }


    public void request(String url, OnCallBack onCallBack) {
        request(url, Method.GET, onCallBack);
    }

    public void request(String url, Method method, OnCallBack onCallBack) {
        if (TextUtils.isEmpty(url)) {
            throw new RuntimeException("url is empty");
        } else {
            String m = "GET";
            if(method == Method.GET){
                m = "GET";
            }else if(method == Method.POST){
                m = "POST";
            }
            new AsyTask(onCallBack).execute(url, m);
        }
    }


    public class Result {
        public int code;
        public String result;

        public int getCode() {
            return code;
        }

        public void setCode(int code) {
            this.code = code;
        }

        public Object getResult() {
            return result;
        }

        public void setResult(String result) {
            this.result = result;
        }

        public boolean isOk() {
            return code == 200;
        }
    }


    public class AsyTask extends AsyncTask<String, Void, Object> {
        private OnCallBack onCallBack;
        private HttpURLConnection urlConnection;


        public AsyTask(OnCallBack onCallBack) {
            this.onCallBack = onCallBack;
        }

        @Override
        protected void onPreExecute() {

            if (onCallBack != null) {
                NetworkInfo networkInfo = onCallBack.getNetWorkInfo();
                if (networkInfo == null
                        || !networkInfo.isConnected()) {
                    Result result = new Result();
                    result.code = OnCallBack.ERROR;
                    onCallBack.onResuLtOnCallBack(result);
                    cancel(true);
                    return;
                }
            }
        }

        @Override
        protected Object doInBackground(String... params) {
            Result result = new Result();
            if (params != null) {
                String u = params[0];
                String RequestMethod = TextUtils.isEmpty(params[1]) ? "GET" : params[1];
                if (!TextUtils.isEmpty(u)) {
                    try {
                        URL url = new URL(u);
                        urlConnection = (HttpURLConnection) url.openConnection();
                        urlConnection.setConnectTimeout(3000);
                        urlConnection.setReadTimeout(3000);
                        urlConnection.setRequestProperty("Content-Type", " application/json");//設定 請求格式 json,也可以設定xml格式的
                        urlConnection.setRequestProperty("Accept-Charset", "utf-8");  //設置編碼語言
                        urlConnection.setRequestProperty("X-Auth-Token", "token");  //設置請求的token
                        urlConnection.setRequestProperty("Connection", "keep-alive");  //設置連接的狀態
                        urlConnection.setRequestMethod(RequestMethod);
                        urlConnection.setDoOutput(true);

                        if("POST".equals(RequestMethod)){
                            OutputStream outputStream = null;
                            try {
                                Map<String,String> pMaps = onCallBack.getParmas();
                                if(pMaps != null){
                                    String p = getParmas(pMaps);
                                    if(!TextUtils.isEmpty(p)){
                                        byte[] bypes = p.toString().getBytes();
                                        outputStream = urlConnection.getOutputStream();
                                        outputStream .write(bypes);// 輸入參數
                                    }
                                }
                            }catch (Exception e){
                                Log.e(TAG,e.getMessage());
                            }finally {
                                if(outputStream != null){
                                    outputStream.close();
                                }
                            }
                        }

                        urlConnection.connect();
                        if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                            InputStream inputStream = urlConnection.getInputStream();
                            if (inputStream != null) {
                                String res = getResult(inputStream);
                                result.code = urlConnection.getResponseCode();
                                result.result = res;
                            }
                        } else {
                            result.code = urlConnection.getResponseCode();//響應失敗
                        }
                        onCallBack.onResuLtOnCallBack(result);
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (urlConnection != null)
                            urlConnection.disconnect();
                    }
                }
            }
            return result;
        }


        private String getParmas(Map<String,String> map){
            if(map != null && map.size() > 0){
                StringBuffer stringBuffer = new StringBuffer();
                for(Map.Entry<String, String> entry : map.entrySet()){
                    stringBuffer.append(entry.getKey());
                    stringBuffer.append("=");
                    stringBuffer.append(entry.getValue());
                    stringBuffer.append("&");
                }
                return stringBuffer.toString();
            }
            return null;
        }

        public String getResult(InputStream inputStream) {
            StringBuffer stringBuffer = new StringBuffer();
            if (inputStream != null) {
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                int count = 0;
                char[] bytes = new char[1024];
                try {
                    while ((count = inputStreamReader.read(bytes)) != -1) {
                        stringBuffer.append(bytes, 0, count);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return stringBuffer.toString();
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
        }
    }
}

工具類:

package com.example.Util;

public class NetWorUtil {
    private static NetWork instance = null;

    public static NetWork getInstance(){
        if(instance == null){
            synchronized (NetWorUtil.class){
                if(instance == null){
                    instance = new NetWork();
                }
            }
        }
        return instance;
    }
}

測試 (隨便找了個api):

NetWorUtil.getInstance().request(url, NetWork.Method.POST, new NetWork.OnCallBack() {

                    @Override
                    public NetworkInfo getNetWorkInfo() {
                        ConnectivityManager connectivityManager =
                                (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
                        return networkInfo;
                    }

                    @Override
                    public void onResuLtOnCallBack(Object res) {
                        if(res != null){
                            NetWork.Result result = (NetWork.Result) res;
                            Log.d("TAG","result:"+String.valueOf(result.getResult()));
                        }
                    }

                    @Override
                    public Map<String, String> getParmas() {
                        Map<String,String> map = new HashMap<>();
                        map.put("scope","103");
                        map.put("format","json");
                        map.put("appid","379020");
                        map.put("bk_key","接口");
                        map.put("bk_length","600");
                        return map;
                    }
                });

只是實現的簡單的請求,後續再完善。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章