AggH5HttpUtils.java 8.4 KB
package com.agg.h5game.tools.http;

import android.app.Activity;
import android.os.AsyncTask;

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

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class AggH5HttpUtils extends AsyncTask<String, Integer, AggH5ResResult> {
    QNHttpCallBack qnHttpCallBack;
    Activity activity;

    AggH5ResResult beginGetRequest(String urlAddress, String parame) {
        AggH5ResResult responeResult = new AggH5ResResult(-1);
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL(urlAddress);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(30 * 1000);
            httpURLConnection.setReadTimeout(30 * 1000);
            httpURLConnection.setRequestMethod("GET");
            InputStream is = httpURLConnection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is,
                    "UTF-8"));
            String response = "";
            String readLine = null;
            while ((readLine = br.readLine()) != null) {
                response = response + readLine;
            }
            is.close();
            br.close();
            response = new String(response.getBytes(), "utf-8");
            responeResult.setStatus(0);
            responeResult.setResult(response);
        } catch (IOException e) {
            responeResult.setResult(e.getLocalizedMessage());
        } finally {
            if (httpURLConnection != null) {
                // 释放资源
                httpURLConnection.disconnect();
            }
        }
        return responeResult;
    }

    AggH5ResResult beginPostRequest(String urlAddress, String parame) {
        AggH5ResResult responeResult = new AggH5ResResult(-1);
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL(urlAddress);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(30 * 1000);
            httpURLConnection.setReadTimeout(30 * 1000);
            httpURLConnection.setRequestMethod("POST");
            DataOutputStream data = new DataOutputStream(httpURLConnection.getOutputStream());
            data.writeBytes(parame);
            InputStream is = httpURLConnection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is,
                    "UTF-8"));
            String response = "";
            String readLine = null;
            while ((readLine = br.readLine()) != null) {
                response += readLine;
            }
            is.close();
            br.close();
            response = new String(response.getBytes(), "utf-8");

            responeResult.setStatus(0);
            responeResult.setResult(response);

        } catch (IOException e) {
            responeResult.setResult(e.getLocalizedMessage());
        } finally {
            if (httpURLConnection != null) {
                // 释放资源
                httpURLConnection.disconnect();
            }
        }
        return responeResult;
    }


    String getParams(JSONObject clientData) {
        if (clientData == null) {
            return null;
        }
        String data = clientData.toString();
        try {
            data = URLEncoder.encode(clientData.toString(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return data;
    }

    /**
     * 把游戏发来的数据进行处理,拼接成与服务器交互进行get请求的字符串
     *
     * @param data 游戏传来的数据
     * @return str 返回排序过的一个字符串
     */
    public static String jsonToString(JSONObject data) {
        JSONObject jsonObject = new JSONObject();
        jsonObject = data;
        Iterator<String> sIterator = jsonObject.keys();
        Map<String, String> map = new TreeMap<String, String>(
                new Comparator<String>() {
                    @Override
                    public int compare(String obj1, String obj2) {
                        return obj1.compareTo(obj2);
                    }
                });
        String str = "";
        while (sIterator.hasNext()) {
            // 获得key
            String key = sIterator.next();
            if (jsonObject.isNull(key)) {
                continue;
            }
            // 根据key获得value, value也可以是JSONObject,JSONArray,使用对应的参数接收即可
            map.put(key, jsonObject.optString(key));
        }
        Set<String> keySet = map.keySet();
        Iterator<String> iter = keySet.iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            if (map.isEmpty()) {
                continue;
            }
            String mapValue = map.get(key);
            try {
                str = str + key + "=" + URLEncoder.encode(mapValue, "UTF-8") + "&";
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return str;
    }


    /**
     * 请求
     */
    public void connect(String urlAddress, String method, JSONObject parame,
                        Activity activity, QNHttpCallBack httpCallBack) {
        if (method == "get") {
            qnHttpCallBack = httpCallBack;
            this.activity = activity;
            // progressDialog = ProgressDialog.show(activity, null, null);
            String client = getParams(parame);
            if (urlAddress == null || urlAddress.length() == 0) {
                return;
            }
            if (parame == null) {
                this.execute(urlAddress, null, "get");
            } else {
                this.execute(urlAddress, client, "get");
            }
        } else if (method == "post") {
            qnHttpCallBack = httpCallBack;
            this.activity = activity;
            // progressDialog = ProgressDialog.show(activity, null, null);
            String client = AggH5HttpUtils.jsonToString(parame);
            if (urlAddress == null || urlAddress.length() == 0) {
                return;
            }
            if (parame == null) {
                this.execute(urlAddress, null, "post");
            } else {
                this.execute(urlAddress, client, "post");
            }
        }
    }


    @Override
    protected AggH5ResResult doInBackground(String... strings) {
        if (strings[2] == "get") {
            return beginGetRequest(strings[0], strings[1]);
        } else if (strings[2] == "post") {
            return beginPostRequest(strings[0], strings[1]);
        }
        return beginPostRequest(strings[0], strings[1]);
    }

    @Override
    protected void onPostExecute(AggH5ResResult result) {
        super.onPostExecute(result);
        if (result.getStatus() == 0) {
            JSONObject rObject = null;
            try {

                rObject = new JSONObject(result.getResult());
                if (rObject.getInt("code") == 0) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("msg", "" + rObject.optString("msg"));
                    qnHttpCallBack.onFailure(jsonObject);
                    return;
                }

                if (qnHttpCallBack == null) {
                    return;
                }
                qnHttpCallBack.onSuccess(rObject);

            } catch (JSONException e) {

                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("catchMsg", result.getResult());
                    qnHttpCallBack.onFailure(jsonObject);
                } catch (JSONException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

            }

        } else {
            JSONObject json = new JSONObject();
            try {
                json.put("msg", "网络错误");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            qnHttpCallBack.onFailure(json);
        }
    }
}