1. 程式人生 > >android http請求訪問介面的封裝

android http請求訪問介面的封裝

轉自 https://www.cnblogs.com/you411305469/p/5212479.html

裡面介紹了實用的兩種

要特別注意,向php請求資料是表單型別的資料
application/x-www-form-urlencoded

import android.os.AsyncTask;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

/**
 * @author Admin
 * @version $Rev$
 * @des ${TODO}
 * @updateAuthor $Author$
 * @updateDes ${TODO}
 */
public class HttpConnection {

    /**
     * 升級版介面
     *
     * @param url
     * @param method
     * @param successCallback
     * @param failCallback
     * @param map
     */
    public HttpConnection(final String url, final HttpMethod method,
                         final SuccessCallback successCallback,
                         final FailCallback failCallback, final Map<String, String> map) {
        new AsyncTask<Void, Void, String>() {

            @Override
            protected String doInBackground(Void... params) {
                StringBuffer sb = new StringBuffer();
                String realString = "";
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    sb.append(entry.getKey()).append("=")
                            .append(entry.getValue()).append("&");
                }
                realString = sb.toString().substring(0,
                        sb.toString().length() - 1);

                try {
                    URLConnection uc;
                    switch (method) {
                        case POST:
                            uc = new URL(url).openConnection();
                            uc.setDoOutput(true);
                            uc.setConnectTimeout(5000);
                            BufferedWriter bw = new BufferedWriter(
                                    new OutputStreamWriter(uc.getOutputStream(),
                                            "utf-8"));
                            bw.write(realString);
                            bw.flush();
                            break;

                        default:
                            uc = new URL(url + "?" + realString).openConnection();

                            uc.setConnectTimeout(5000);
                            uc.setRequestProperty("apikey",
                                    "2f50fafc573e93a725e277b073d9c5dd");
                            break;
                    }
                    System.out.println("Request url:" + uc.getURL());
                    System.out.println("Request date:" + realString);
                    System.out.println("Result status:"
                            + ((HttpURLConnection) uc).getResponseCode());
                    if (((HttpURLConnection) uc).getResponseCode() == 200) {
                        BufferedReader br = new BufferedReader(
                                new InputStreamReader(uc.getInputStream(),
                                        "utf-8"));
                        StringBuffer result = new StringBuffer();
                        String line = "";
                        while ((line = br.readLine()) != null) {
                            result.append(line);
                        }
                        System.out.println("Result:" + result);
                        return result.toString();
                    } else {
                        System.out.println("Result:"
                                + ((HttpURLConnection) uc).getResponseCode());
                    }

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(String result) {
                if (result != null) {
                    try {
                        JSONObject json = new JSONObject(result);
                        if (successCallback != null) {
                            successCallback.onSuccess(result);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                } else {
                    if (failCallback != null) {
                        failCallback.onFail();
                    }
                }
                super.onPostExecute(result);

            }
        }.execute();
    }

    /**
     * json型介面升級版
     *
     * @param url
     * @param successCallback
     * @param failCallback
     * @param json map
     */
    public HttpConnection(final String url,
                         final SuccessCallback successCallback,
                         final FailCallback failCallback, final String json) {
        new AsyncTask<Void, Void, String>() {

            @Override
            protected String doInBackground(Void... params) {
                try {
                    HttpURLConnection uc = (HttpURLConnection) new URL(url)
                            .openConnection();
                    //開啟輸出流
                    uc.setDoOutput(true);
                    //開啟輸入流
                    uc.setDoInput(true);
                    uc.setInstanceFollowRedirects(true);
                    //post方式
                    uc.setRequestMethod("POST");
                    //超時
                    uc.setConnectTimeout(5000);
                    //禁止使用快取
                    uc.setUseCaches(false);
                    //接收字串型別資料用json
                    uc.setRequestProperty("Accept", "application/json");
                    //請求的內容為表單型別資料
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    //設定utf8
                    uc.setRequestProperty("Charset", "UTF-8");

//                    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(uc.getOutputStream(),"utf-8"));
//                    bw.write(json);
//                    bw.flush();
                    /**
                     * 請求資料(表單型別的或json型別的資料)
                     */
                    OutputStreamWriter writer = new OutputStreamWriter(uc.getOutputStream());
                    //傳送引數
                    writer.write(json);
                    //清理當前編輯器的左右緩衝區,並使緩衝區資料寫入基礎流
                    writer.flush();



                    System.out.println("Request url:" + uc.getURL());
                    System.out.println("Request date:" + json);

                    //判斷接收資料,為json格式
                    if (uc.getResponseCode() == 200) {
                        BufferedReader br = new BufferedReader(
                                new InputStreamReader(uc.getInputStream(),
                                        "utf-8"));
                        StringBuffer result = new StringBuffer();
                        String line = "";
                        while ((line = br.readLine()) != null) {
                            result.append(line);
                        }
                        System.out.println("Result:" + result);
                        return result.toString();
                    } else {
                        System.out.println("uc.getResponseCode()=="
                                + uc.getResponseCode());
                        System.out.println("uc.getResponseMessage()=="
                                + uc.getResponseMessage());
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                return null;
            }

            @Override
            protected void onPostExecute(String result) {
                if (result != null) {
                    if (successCallback != null) {
                        successCallback.onSuccess(result);
                    }
                } else {
                    if (failCallback != null) {
                        failCallback.onFail();
                    }
                }
                super.onPostExecute(result);

            }
        }.execute();
    }



    public static interface SuccessCallback {
        void onSuccess(String result);
    }

    public static interface FailCallback {
        void onFail();
    }

}

以上類需要用到HttpMethod

public enum HttpMethod {
    POST,GET
}

以上的類就是http訪問介面的類,以下就來舉些例子吧:

/**
     * 積分商品列表
     */
    private void initData(int flag) {
        private String url = "http://192.168.1.11/xxx";
        Map<String, String> params = new HashMap<String, String>();
        params.put("types", "0");
        params.put("isonsail", "0");
        params.put("rowStart",  "0");
        params.put("rowEnd",  "20");
        new NetConnection(url, "post",
                new NetConnection.SuccessCallback() {
 
                    @Override
                    public void onSuccess(String result) {
                         
                    }
                }, new NetConnection.FailCallback() {
 
                    @Override
                    public void onFail() {
                         
                    }
                }, params);
    }

還有一種是json型的入參的:

/**
     * 發起全車診斷 介面描述:該介面用於向 iOBD裝置下發診斷指令
     */
    public void check() {
        JSONObject param = new JSONObject();
        try {
            param.put("appkey", Config.getAppKey(this));
            param.put("imei", Config.getImei(this));
        } catch (Exception e) {
            e.printStackTrace();
        }
        new NetConnection(Config.SERVER_URL + "diagnosis/trigge",
                new NetConnection.SuccessCallback() {
                    @Override
                    public void onSuccess(String result) {
                         
                    }
                }, new NetConnection.FailCallback() {
                    @Override
                    public void onFail() {
                         
                    }
                }, param.toString());
    }