zblibrary.demo.manager.HttpRequest.java Source code

Java tutorial

Introduction

Here is the source code for zblibrary.demo.manager.HttpRequest.java

Source

/*Copyright 2015 TommyLemon(https://github.com/TommyLemon)
    
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    
http://www.apache.org/licenses/LICENSE-2.0
    
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/

package zblibrary.demo.manager;

import android.content.Context;
import android.os.AsyncTask;
import android.text.TextUtils;

import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONObject;

import java.io.IOException;
import java.net.CookieHandler;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLSocketFactory;

import zblibrary.demo.application.DemoApplication;
import zuo.biao.library.util.Log;
import zuo.biao.library.util.MD5Util;
import zuo.biao.library.util.SSLUtil;
import zuo.biao.library.util.SettingUtil;
import zuo.biao.library.util.StringUtil;

/**HTTP
 * @author Lemon
 * @use HttpRequest.getInstance().xxxMethod  > onHttpRequestSuccessonHttpRequestError?HTTP
 * @must getTokengetResponseCodegetResponseDataTODO
 */
public class HttpRequest {
    private static final String TAG = "HttpRequest";

    /**?
     */
    public interface OnHttpResponseListener {
        /**
         * @param requestCode ??Activity??????
         * @param resultCode ??
         * @param resultData ?Json
         */
        void onHttpRequestSuccess(int requestCode, int resultCode, String resultData);

        /**
         * @param requestCode ??Activity??????
         * @param exception OKHTTP
         */
        void onHttpRequestError(int requestCode, Exception exception);
    }

    private Context context;
    private static HttpRequest httpRequest;// ?
    private static SSLSocketFactory socketFactory;// ?

    private HttpRequest(Context context) {
        this.context = context;

        try {
            //TODO ???demo.cerdemo.cer?????assets?????
            socketFactory = SSLUtil.getSSLSocketFactory(context.getAssets().open("demo.cer"));
        } catch (Exception e) {
            Log.e(TAG, "private HttpRequest()  try {"
                    + "  socketFactory = SSLUtil.getSSLSocketFactory(context.getAssets().open(\"demo.cer\"));\n"
                    + "\t\t} catch (Exception e) {\n" + e.getMessage());
        }
    }

    public synchronized static HttpRequest getInstance() {
        if (null == httpRequest) {
            httpRequest = new HttpRequest(DemoApplication.getInstance());
        }
        return httpRequest;
    }

    /**URL???*/
    public static final String URL_BASE = SettingUtil.getCurrentServerAddress(DemoApplication.getInstance());

    //user<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    public static final int PAGE_NUM_0 = 0;
    public static final String KEY_PAGE_NUM = "pageNum";

    public static final String KEY_RANGE = "range";

    public static final String KEY_ID = "id";
    public static final String KEY_USER_ID = "userId";
    public static final String KEY_CURRENT_USER_ID = "currentUserId";

    public static final String KEY_NAME = "name";
    public static final String KEY_PHONE = "phone";
    public static final String KEY_AUTH_CODE = "authCode";

    public static final String KEY_SEX = "sex";
    public static final int SEX_MAIL = 1;
    public static final int SEX_FEMAIL = 2;
    public static final int SEX_ALL = 3;

    public static final String KEY_TYPE = "type";
    public static final String KEY_FLAG = "flag";
    public static final String KEY_ADD = "add";
    public static final String KEY_DELETE = "delete";

    /**
     * TODO ???
     */
    private static final String URL_GET_USER = URL_BASE + "user/infomation";

    /**?
     * @param userId
     * @param requestCode
     * @param listener
     */
    public void getUser(long userId, final int requestCode, final OnHttpResponseListener listener) {
        List<Parameter> paramList = new ArrayList<Parameter>();
        addExistParameter(paramList, KEY_CURRENT_USER_ID, DemoApplication.getInstance().getCurrentUserId());
        addExistParameter(paramList, KEY_USER_ID, userId);
        httpPost(paramList, URL_GET_USER, requestCode, listener);
    }

    public static final int RESULT_GET_USER_SUCCEED = 100;

    public static final int USER_LIST_RANGE_ALL = 0;
    public static final int USER_LIST_RANGE_RECOMMEND = 1;

    /**?
     * @param range
     * @param pageNum
     * @param requestCode
     * @param listener
     */
    public void getUserList(int range, int pageNum, final int requestCode, final OnHttpResponseListener listener) {
        List<Parameter> paramList = new ArrayList<Parameter>();
        addExistParameter(paramList, KEY_CURRENT_USER_ID, DemoApplication.getInstance().getCurrentUserId());
        addExistParameter(paramList, KEY_RANGE, range);
        addExistParameter(paramList, KEY_PAGE_NUM, pageNum);

        httpGet(paramList, URL_GET_USER, requestCode, listener);
    }

    public static final int RESULT_GET_USER_LIST_SUCCEED = 110;

    //user>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    //? <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    /**value?
     * @param list
     * @param key
     * @param value
     */
    private void addExistParameter(List<Parameter> list, String key, Object value) {
        if (list == null) {
            list = new ArrayList<>();
        }
        if (StringUtil.isNotEmpty(key, true) && StringUtil.isNotEmpty(value, true)) {
            list.add(new Parameter(key, value));
        }
    }

    /**
     * @param paramList
     *            ??
     * @param url
     *            ?url
     * @param requestCode
     *            ?onActivityResult??activity??<br/>
     *             ???
     *            {@link OnHttpResponseListener#onHttpRequestError(int, Exception)}
     *             <br/>
     *            {@link OnHttpResponseListener#onHttpRequestError(int, Exception)}
     * <br/>
     *            activity?requestCode??serverResultCode???
     *            json?json? 
     *
     * @param listener
     */
    private void httpPost(final List<Parameter> paramList, final String url, final int requestCode,
            final OnHttpResponseListener listener) {

        new AsyncTask<Void, Void, Exception>() {

            int resultCode;
            String resultData;

            @Override
            protected Exception doInBackground(Void... params) {
                OkHttpClient client = getHttpClient(url);
                if (client == null) {
                    return new Exception("httpPost  AsyncTask.doInBackground  client == null >> return;");
                }

                FormEncodingBuilder fBuilder = new FormEncodingBuilder();
                if (paramList != null) {
                    for (Parameter p : paramList) {
                        fBuilder.add(p.key, p.value);
                    }
                }

                JSONObject jsonObject = null;
                try {
                    jsonObject = getResponseObject(client,
                            new Request.Builder().addHeader("token", getToken(paramList))
                                    .url(StringUtil.getNoBlankString(url)).post(fBuilder.build()).build());
                } catch (Exception e) {
                    Log.e(TAG, "httpPost  AsyncTask.doInBackground  try {  jsonObject = getResponseObject(..."
                            + "} catch (Exception e) {\n" + e.getMessage());
                    return e;
                }

                resultCode = getResponseCode(jsonObject);
                resultData = getResponseData(jsonObject);

                return null;
            }

            @Override
            protected void onPostExecute(Exception exception) {
                super.onPostExecute(exception);
                httpPostExecute(listener, requestCode, exception, resultCode, resultData);
            }

        }.execute();
    }

    /**
     * @param paramList
     *            ??
     * @param url
     *            ?url
     * @param requestCode
     *            ?onActivityResult??activity??<br/>
     *             ???
     *            {@link OnHttpResponseListener#onHttpRequestError(int, Exception)}
     *             <br/>
     *            {@link OnHttpResponseListener#onHttpRequestError(int, Exception)}
     * <br/>
     *            activity?requestCode??serverResultCode???
     *            json?json? 
     *
     * @param listener
     */
    private void httpGet(final List<Parameter> paramList, final String url, final int requestCode,
            final OnHttpResponseListener listener) {

        new AsyncTask<Void, Void, Exception>() {

            int resultCode;
            String resultData;

            @Override
            protected Exception doInBackground(Void... params) {
                OkHttpClient client = getHttpClient(url);
                if (client == null) {
                    return new Exception("httpGet  AsyncTask.doInBackground  client == null >> return;");
                }

                StringBuffer sb = new StringBuffer();
                sb.append(StringUtil.getNoBlankString(url));
                if (paramList != null) {
                    Parameter parameter;
                    for (int i = 0; i < paramList.size(); i++) {
                        parameter = paramList.get(i);
                        sb.append(i <= 0 ? "?" : "&");
                        sb.append(parameter.key);
                        sb.append("=");
                        sb.append(parameter.value);
                    }
                }

                JSONObject jsonObject = null;
                try {
                    jsonObject = getResponseObject(client, new Request.Builder()
                            .addHeader("token", getToken(paramList)).url(sb.toString()).build());
                } catch (Exception e) {
                    Log.e(TAG, "httpGet  AsyncTask.doInBackground  try {  jsonObject = getResponseObject(..."
                            + "} catch (Exception e) {\n" + e.getMessage());
                    return e;
                }

                resultCode = getResponseCode(jsonObject);
                resultData = getResponseData(jsonObject);

                return null;
            }

            @Override
            protected void onPostExecute(Exception exception) {
                super.onPostExecute(exception);
                httpPostExecute(listener, requestCode, exception, resultCode, resultData);
            }

        }.execute();

    }

    //httpGet/httpPost  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    /**
     * @param url
     * @return
     */
    private OkHttpClient getHttpClient(String url) {
        Log.i(TAG, "getHttpClient  url = " + url);
        if (StringUtil.isNotEmpty(url, true) == false) {
            Log.e(TAG, "getHttpClient  StringUtil.isNotEmpty(url, true) == false >> return null;");
            return null;
        }

        OkHttpClient client = new OkHttpClient();
        client.setCookieHandler(new HttpHead());
        client.setConnectTimeout(15, TimeUnit.SECONDS);
        client.setWriteTimeout(10, TimeUnit.SECONDS);
        client.setReadTimeout(10, TimeUnit.SECONDS);
        //https?,??,???
        if (url.startsWith(StringUtil.URL_PREFIXs) && socketFactory != null) {
            client.setSslSocketFactory(socketFactory);
        }

        return client;
    }

    /**
     * @param paramList
     * @must demo_***?
     * @return
     */
    public String getToken(List<Parameter> paramList) {
        if (paramList == null) {
            return "";
        }

        String token = "";
        Parameter p;
        for (int i = 0; i < paramList.size(); i++) {
            if (i > 0) {
                token += "&";
            }
            p = paramList.get(i);
            token += (p.key + "=" + p.value);
        }
        token += "demo_***";//TODO demo_***?
        return MD5Util.MD5(token);
    }

    private static final String KEY_COOKIE = "cookie";

    /**
     * @return
     */
    public String getCookie() {
        return context.getSharedPreferences(KEY_COOKIE, Context.MODE_PRIVATE).getString(KEY_COOKIE, "");
    }

    /**
     * @param value
     */
    public void saveCookie(String value) {
        context.getSharedPreferences(KEY_COOKIE, Context.MODE_PRIVATE).edit().putString(KEY_COOKIE, value).commit();
    }

    /**
     * @param client
     * @param request
     * @return
     * @throws Exception
     */
    private JSONObject getResponseObject(OkHttpClient client, Request request) throws Exception {
        if (client == null || request == null) {
            Log.e(TAG, "getResponseObject  client == null || request == null >> return null;");
            return null;
        }
        Response response = client.newCall(request).execute();
        return response.isSuccessful() ? new JSONObject(response.body().string()) : null;
    }

    /**
     * @param object
     * @return
     */
    private int getResponseCode(JSONObject object) {
        try {
            return object.getInt("result");//TODO result ?key
        } catch (Exception e) {
            Log.e(TAG, "getResponseCode  try { return object.getInt(result);" + "} catch (Exception e) {\n"
                    + e.getMessage());
        }
        return 0;
    }

    /**
     * @param object
     * @return
     */
    private String getResponseData(JSONObject object) {
        try {
            return object.getString("data");//TODO data ?key
        } catch (Exception e) {
            Log.e(TAG, "httpPost  getResponseData  try { return object.getString(data);"
                    + "} catch (Exception e) {\n" + e.getMessage());
        }
        return null;
    }

    /**
     * @param listener
     * @param requestCode
     * @param exception
     * @param resultCode
     * @param resultData
     */
    private void httpPostExecute(OnHttpResponseListener listener, int requestCode, Exception exception,
            int resultCode, String resultData) {
        if (listener == null) {
            Log.e(TAG, "httpPostExecute  listener == null >> return;");
            return;
        }

        if (exception == null || resultCode > 0 || StringUtil.isNotEmpty(resultData, true)) {
            Log.i(TAG, "httpPostExecute requestCode = " + requestCode + "; resultCode = " + resultCode
                    + "; result = <<<<<<<<<<<<<<<<<<<< \n" + resultData + "\n>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
            listener.onHttpRequestSuccess(requestCode, resultCode, resultData);
        } else {
            Log.w(TAG, "httpPostExecute requestCode = " + requestCode + "\n  exception = <<<<<<<<<<<<<<<<<<<< \n"
                    + exception.getMessage() + "\n>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
            listener.onHttpRequestError(requestCode, exception);
        }
    }

    //httpGet/httpPost  >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    public static class Parameter {
        public final String key;
        public final String value;

        public Parameter(String key, String value) {
            super();
            this.key = StringUtil.getNoBlankString(key);
            this.value = StringUtil.getNoBlankString(value);
        }

        /**
         * @author lemon
         * @param key
         * @param value
         */
        public Parameter(String key, Object value) {
            this(key, StringUtil.getTrimedString(value));
        }
    }

    public class HttpHead extends CookieHandler {
        public HttpHead() {
        }

        @Override
        public Map<String, List<String>> get(URI uri, Map<String, List<String>> requestHeaders) throws IOException {
            String cookie = getCookie();
            Map<String, List<String>> map = new HashMap<String, List<String>>();
            map.putAll(requestHeaders);
            if (!TextUtils.isEmpty(cookie)) {
                List<String> cList = new ArrayList<String>();
                cList.add(cookie);
                map.put("Cookie", cList);
            }
            return map;
        }

        @Override
        public void put(URI uri, Map<String, List<String>> responseHeaders) throws IOException {
            List<String> list = responseHeaders.get("Set-Cookie");
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    String cookie = list.get(i);
                    if (cookie.startsWith("JSESSIONID")) {
                        saveCookie(list.get(i));
                        break;
                    }
                }
            }
        }

    }

    //? >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

}