QnBarApi.java 8.71 KB
/*
 *  Copyright (c)  2016.  wugian
 *  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 com.xgimi.gimicinema.api;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import com.gimi.common.cinema.utils.NetStatusUtils;
import com.xgimi.gimicinema.api.converter.StringConverterFactory;
import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.File;
import java.io.IOException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import static com.xgimi.gimicinema.api.IQnBarApi.QN_API_BASE_URL;

/**
 * Created by wugian on 2016/11/8
 */
public class QnBarApi {

    private IQnBarApi qnBarApi;

    public QnBarApi(Context context) {
        Interceptor interceptor = new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                okhttp3.Response response = chain.proceed(request);

                if (NetStatusUtils.isAvailableByPing()) {
                    String cacheControl = request.cacheControl().toString();
                    if (TextUtils.isEmpty(cacheControl)) {
                        cacheControl = "public, max-age=60";//cache 60s
                    }

                    return response.newBuilder()
                            .header("Cache-Control", cacheControl)
                            .removeHeader("Pragma")
                            .build();
                } else {
                    request = request.newBuilder()
                            .cacheControl(CacheControl.FORCE_CACHE)//cache max age
                            .build();
                    String cacheControl = request.cacheControl().toString();

                    return response.newBuilder()
                            .header("Cache-Control", cacheControl)
                            .removeHeader("Pragma")
                            .build();
                }

            }
        };
        //设置缓存路径
        File httpCacheDirectory = new File(context.getCacheDir(), "responses");
        //设置缓存 10M
        Cache cache = new Cache(httpCacheDirectory, 10 * 1024 * 1024);
        //创建OkHttpClient,并添加拦截器和缓存代码
        OkHttpClient mOkHttpClient;

        OkHttpClient.Builder mBuilder = new OkHttpClient.Builder();
        mBuilder/*.sslSocketFactory(createSSLSocketFactory())
                .hostnameVerifier(new TrustAllHostnameVerifier())*/
                .cache(cache)
                .addInterceptor(interceptor);
        mOkHttpClient = mBuilder.build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(QN_API_BASE_URL)
//                .addConverterFactory(GsonConverterFactory.create())
                .addConverterFactory(StringConverterFactory.create())
                .client(mOkHttpClient)
                .build();

        qnBarApi = retrofit.create(IQnBarApi.class);

//        Gson gson = new GsonBuilder().registerTypeHierarchyAdapter(List.class, new JsonDeserializer<List<?>>() {
//            @Override
//            public List<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
//                if (json.isJsonArray()) {
//                    context.
//                    JsonArray array = json.getAsJsonArray();
//                    Type itemType = ((ParameterizedType) typeOfT).getActualTypeArguments()[0];
//                    List list = new ArrayList<>();
//                    for (int i = 0; i < array.size(); i++) {
//                        JsonElement element = array.get(i);
//                        Object item = context.deserialize(element, itemType);
//                        list.add(item);a
//                    }
//                    return list;
//                } else {
//                    //和接口类型不符,返回空List
//                    return Collections.EMPTY_LIST;
//                }
//            }
//        }).create();


        Retrofit retrofit1 = new Retrofit.Builder()
                .baseUrl("https://api.github.com")
                .addConverterFactory(GsonConverterFactory.create())
                .addConverterFactory(StringConverterFactory.create())
                .client(mOkHttpClient)
                .build();

        GitHub git = retrofit1.create(GitHub.class);
//        Call<List<Contributor>> contributors = git.contributors("square", "retrofit");
//        contributors.enqueue(new Callback<List<Contributor>>() {
//            @Override
//            public void onResponse(Call<List<Contributor>> call, Response<List<Contributor>> response) {
//                Log.d("TAG", "onResponse:" + response.body());
//            }
//
//            @Override
//            public void onFailure(Call<List<Contributor>> call, Throwable t) {
//                Log.d("TAG", "onFailure:" + t.getMessage());
//            }
//        });
        Call<String> contributor = git.contributor("square", "retrofit");
        contributor.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Log.d("TAG", "onResponse:" + response.body());
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                Log.d("TAG", "onFailure:" + t.getMessage());
            }
        });

        getMessage("LETEST");

    }

    public void getMessage(String pid) {
        Call<String> call = qnBarApi.getMessage(pid);
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Log.d("TAG", "onResponse:" + response.body());
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                Log.d("TAG", "onFailure:" + t.getMessage());
            }
        });
    }

    public void getStatus(String pid) {
        Call<String> call = qnBarApi.getStatus(pid);
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Log.d("TAG", "onResponse:" + response.body());
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                Log.d("TAG", "onFailure:" + t.getMessage());
            }
        });
    }

    /**
     * 默认信任所有的证书
     * TODO 最好加上证书认证,主流App都有自己的证书
     *
     * @return
     */
    @SuppressLint("TrulyRandom")
    private static SSLSocketFactory createSSLSocketFactory() {

        SSLSocketFactory sSLSocketFactory = null;

        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new TrustAllManager()},
                    new SecureRandom());
            sSLSocketFactory = sc.getSocketFactory();
        } catch (Exception e) {
        }

        return sSLSocketFactory;
    }

    private static class TrustAllManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType)

                throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }

    private static class TrustAllHostnameVerifier implements HostnameVerifier {

        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }

    }
}