import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import static android.content.Context.MODE_PRIVATE;
/**
* Created by Administrator on 2017/7/13.
*/
public class CommonHttp {
private CommonHttpCallback mCallback;
public static final String cookie = "Set-Cookie";
public static String COOKIEVALUE;
public static String TYPEVALUE=BuildConfig.BUILD_TYPE;
private String baseUrl;
private static OkHttpClient client;
private static Retrofit retrofit;
public CommonHttp(CommonHttpCallback callback, String baseUrl) {
this.baseUrl = baseUrl;
mCallback = callback;
if(retrofit==null) {
OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder();
Dispatcher dispatcher = new Dispatcher();
dispatcher.setMaxRequests(128);
dispatcher.setMaxRequestsPerHost(32);
httpBuilder.dispatcher(dispatcher);
httpBuilder.connectionPool(new ConnectionPool(32, 20, TimeUnit.MILLISECONDS));
client = httpBuilder.readTimeout(3, TimeUnit.MINUTES).connectTimeout(3,
TimeUnit.MINUTES).writeTimeout(3, TimeUnit.MINUTES) //设置超时
.build();
retrofit = new Retrofit.Builder().baseUrl(baseUrl).client(client).build();
}
}
public static void setBaseUrl(String baseUrl){
OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder();
Dispatcher dispatcher = new Dispatcher();
dispatcher.setMaxRequests(128);
dispatcher.setMaxRequestsPerHost(32);
httpBuilder.dispatcher(dispatcher);
httpBuilder.connectionPool(new ConnectionPool(32, 20, TimeUnit.MILLISECONDS));
client = httpBuilder.readTimeout(3, TimeUnit.MINUTES).connectTimeout(3,
TimeUnit.MINUTES).writeTimeout(3, TimeUnit.MINUTES) //设置超时
.build();
retrofit = new Retrofit.Builder().baseUrl(baseUrl).client(client).build();
}
public CommonHttp(CommonHttpCallback callback, String baseUrl,boolean isnewbase) {
this.baseUrl = baseUrl;
mCallback = callback;
OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder();
Dispatcher dispatcher = new Dispatcher();
dispatcher.setMaxRequests(128);
dispatcher.setMaxRequestsPerHost(32);
httpBuilder.dispatcher(dispatcher);
httpBuilder.connectionPool(new ConnectionPool(32, 20, TimeUnit.MILLISECONDS));
client = httpBuilder.readTimeout(3, TimeUnit.MINUTES).connectTimeout(3,
TimeUnit.MINUTES).writeTimeout(3, TimeUnit.MINUTES) //设置超时
.build();
retrofit = new Retrofit.Builder().baseUrl(baseUrl).client(client).build();
}
public static void destoryRetrifit(){
retrofit=null;
}
private String TAG = "OKHTTP";
public void doRequest(final Object... objects) {
String url = null;
Map<String, Object> params = null;
// FormBody formBody=null;
RequestBody formBody = null;
Call<ResponseBody> call = null;
switch (objects.length) {
case 1:
url = (String) objects[0];
break;
case 2:
url = (String) objects[0];
params = (Map<String, Object>) objects[1];
formBody = RequestBody.create(okhttp3.MediaType.parse("application/json; " +
"charset=utf-8"), JSON.toJSONString(params));
Log.e("jsonparams", url + "," + JSON.toJSONString(params));
// FormBody.Builder builder = new FormBody.Builder();
// params.putAll(AccountUtil.getOptionalFixedParameters());
// for (HashMap.Entry<String, String> entry :
// params.entrySet()) {
// builder.add(entry.getKey(), entry.getValue());
// }
// formBody=builder.build();
break;
}
// String baseUrl=null;
// try {
// url = URLEncoder.encode(url,"utf-8");
// baseUrl=URLEncoder.encode(Global.requestPath,"utf-8");
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// OkHttpClient okHttpClient = UnsafeOkHttpClient.getUnsafeOkHttpClient();
switch (objects.length) {
case 1:
CommonHttpService callback1 = retrofit.create(CommonHttpService.class);
if (COOKIEVALUE == null) {
call = callback1.get(url);
} else {
HashMap<String,String> headers=new HashMap<>();
headers.put("auth",COOKIEVALUE);
call = callback1.get(url, headers);
}
break;
case 2:
CommonHttpService callback2 = retrofit.create(CommonHttpService.class);
if (COOKIEVALUE == null) {
call = callback2.post(url, formBody);
} else {
HashMap<String,String> headers=new HashMap<>();
headers.put("auth",COOKIEVALUE);
call = callback2.post(url, headers, formBody);
}
break;
}
DebugLog.LogD("请求连接" + url);
DebugLog.LogD("请求cookie:" + COOKIEVALUE);
DebugLog.LogD("请求cookie:" + TYPEVALUE);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.e("请求连接", call.request().url().toString());
if (response != null) {
Message msg = new Message();
msg.obj = response;
mHandler.sendMessage(msg);
} else {
mHandler.sendEmptyMessage(-1);
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("请求失败", t.getMessage());
mHandler.sendEmptyMessage(-1);
}
});
}
Handler mHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message message) {
if (message.what == -1) {
mCallback.requestAbnormal(-1);
return;
}
Response response = (Response) message.obj;
try {
if (response.code() == 200 || response.code() == 204) {
String body = null;
body = ((ResponseBody) response.body()).string();
DebugLog.LogD("请求结果" + body);
int code = getCode(body);
if (code == 200) {
mCallback.requestSeccess(body);
}
} else if (response.code() == 500) {
// Toast.makeText(mContext, getMsg(response.body().string()), Toast
// .LENGTH_SHORT).show();
if (response.body() != null) {
String errbody = ((ResponseBody) response.body()).string();
DebugLog.LogD("请求结果500异常" + errbody);
mCallback.requestFail(-100500, errbody);
} else {
mCallback.requestFail(-1001, "500未知异常");
}
} else {
if (response.body() != null)
DebugLog.LogD("请求结果未知异常" + response.errorBody().string() + ((ResponseBody) response.body()).string());
mCallback.requestAbnormal(response.code());
}
} catch (Exception e) {
DebugLog.LogD("请求结果exception" + e.getMessage());
mCallback.requestFail(-100700, e.getMessage());
e.printStackTrace();
}
}
};
private String getMsg(String json) {
String str = null;
JSONObject object = JSONObject.parseObject(json);
str = object.getString("errmsg");
return str;
}
private int getCode(String json) {
int i = -1;
if (json == null || json.equals("")) {
return -1;
}
JSONObject object = JSONObject.parseObject(json);
i = object.getInteger("errno");
return i;
}
public static String getBodyObj(String json, String objName) {
String body = null;
if (json == null || json.equals("")) {
return null;
}
JSONObject object = JSONObject.parseObject(json);
body = object.getJSONObject(objName).toString();
return body;
}
public static String getBodyArr(String json, String arrName) {
String body = null;
if (json == null || json.equals("")) {
return null;
}
JSONObject object = JSONObject.parseObject(json);
body = object.getJSONArray(arrName).toString();
return body;
}
}
/**
* Created by Administrator on 2017/7/13.
*/
public interface CommonHttpService {
@HTTP(method = "POST", path = "{url}", hasBody = true)
@Headers("ContentType: application/json;charset=UTF-8")
Call<ResponseBody> post(@Path(value = "url", encoded = true) String url,
@HeaderMap() HashMap<String,String> tokens, @Body RequestBody object);
@Streaming
@HTTP(method = "GET", path = "{url}", hasBody = false)
Call<ResponseBody> download(@Path(value = "url", encoded = true) String url, @Header("Cookie") String token);
@Streaming
@HTTP(method = "GET", path = "{url}", hasBody = false)
Call<ResponseBody> download(@Path(value = "url", encoded = true) String url);
// @HTTP(method = "POST",
// path = "{url}",
// hasBody = true)
// Call<ResponseBody> post(@Path(value = "url", encoded = true) String url, @Body RequestBody object);
@HTTP(method = "POST", path = "{url}", hasBody = true)
@Headers("ContentType: application/json;charset=UTF-8")
Call<ResponseBody> post(@Path(value = "url", encoded = true) String url, @Body RequestBody object);
//
// @HTTP(method = "POST",hasBody = true)
// @Headers("ContentType: application/json;charset=UTF-8")
// Call<ResponseBody> postNoUrl( @Body RequestBody object);
//
// @HTTP(method = "POST", path = "/", hasBody = true)
// @Headers("ContentType: application/json;charset=UTF-8")
// Call<ResponseBody> postNoUrl( @Header("token") String token, @Body RequestBody object);
@HTTP(method = "GET", hasBody = false)
Call<ResponseBody> get(@Url String url);
@HTTP(method = "GET", hasBody = false)
Call<ResponseBody> get(@Url String url, @HeaderMap() HashMap<String,String> tokens);
@Multipart
@HTTP(method = "POST", path = "{url}", hasBody = true)
Call<ResponseBody> postFile(@Path(value = "url", encoded = true) String url, @Part List<MultipartBody.Part> parts);
@Multipart
@HTTP(method = "POST", path = "{url}", hasBody = true)
Call<ResponseBody> postFile(@Path(value = "url", encoded = true) String url, @Header("Cookie") String token, @Part List<MultipartBody.Part> parts);
}
public class HttpUtil {
protected String baseUrl;
// public HttpUtil(Context context) {
// this.mContext = context;
// this.baseUrl = getApplicationData(context);
// if (baseUrl == null) {
// throw new FookeyException(20001);
// }
//
// UrlObject.BASEURL = baseUrl;
baseUrl=baseUrl.substring(0,baseUrl.lastIndexOf("/")+1);
// DebugLog.LogE(baseUrl);
// }
public HttpUtil(String baseUrl) {
this.baseUrl = baseUrl;
}
private static String getApplicationData(Context context) {
ApplicationInfo appInfo = null;
try {
appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(),
PackageManager.GET_META_DATA);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return appInfo.metaData.getString("httpaddress");
}
public <T> void getObjectBean(final String url, Map<String, Object> map, final Class<T> t,
final HttpUtilInterface<T> listener) {
new CommonHttp(new CommonHttpCallback() {
@Override
public void requestSeccess(String json) {
T object = (T) JSONObject.parseObject(json, t);
listener.backSuccess((T) object);
}
@Override
public void requestFail(int code,String msg) {
listener.backFail(code,msg);
}
@Override
public void requestAbnormal(int code) {
listener.backAbnormal(code);
}
}, baseUrl).doRequest(url, map);
}
public void getObjectBean(Map<String, Object> map, final HttpUtilInterface listener) {
new CommonHttp(new CommonHttpCallback() {
@Override
public void requestSeccess(String json) {
listener.backSuccess(json);
}
@Override
public void requestFail(int code,String msg) {
listener.backFail(code,msg);
}
@Override
public void requestAbnormal(int code) {
listener.backAbnormal(code);
}
}, baseUrl).doRequest(".", map);
}
public void doGet(final HttpUtilInterface listener) {
new CommonHttp(new CommonHttpCallback() {
@Override
public void requestSeccess(String json) {
listener.backSuccess(json);
}
@Override
public void requestFail(int code,String msg) {
listener.backFail(code,msg);
}
@Override
public void requestAbnormal(int code) {
listener.backAbnormal(code);
}
}, baseUrl).doRequest(".");
}
public void doGet(String url,final HttpUtilInterface listener) {
new CommonHttp(new CommonHttpCallback() {
@Override
public void requestSeccess(String json) {
listener.backSuccess(json);
}
@Override
public void requestFail(int code,String msg) {
listener.backFail(code,msg);
}
@Override
public void requestAbnormal(int code) {
listener.backAbnormal(code);
}
}, baseUrl).doRequest(url);
}
public <T>void doGetObject(String url, final Class<T> t,
final HttpUtilInterface<T> listener) {
new CommonHttp(new CommonHttpCallback() {
@Override
public void requestSeccess(String json) {
T object = (T) JSONObject.parseObject(json, t);
listener.backSuccess((T) object);
}
@Override
public void requestFail(int code,String msg) {
listener.backFail(code,msg);
}
@Override
public void requestAbnormal(int code) {
listener.backAbnormal(code);
}
}, baseUrl).doRequest(url);
}
public <T> void getObjectBean(final Map<String, Object> map, final Class<T> t,
final HttpUtilInterface<T> listener) {
new CommonHttp(new CommonHttpCallback() {
@Override
public void requestSeccess(String json) {
try {
Log.e("backjson", json);
T object = (T) JSONObject.parseObject(json, t);
listener.backSuccess((T) object);
}catch (Exception e){
Log.e("json出错",map.get("biz")+":"+e.getMessage());
}
}
@Override
public void requestFail(int code,String msg) {
listener.backFail(code,msg);
}
@Override
public void requestAbnormal(int code) {
listener.backAbnormal(code);
}
}, baseUrl).doRequest(".", map);
}
public void getObjectBean( String url,Map<String, Object> map, final HttpUtilInterface listener) {
new CommonHttp(new CommonHttpCallback() {
@Override
public void requestSeccess(String json) {
listener.backSuccess(json);
}
@Override
public void requestFail(int code,String msg) {
listener.backFail(code,msg);
}
@Override
public void requestAbnormal(int code) {
listener.backAbnormal(code);
}
}, baseUrl).doRequest(url, map);
}
}