标签:
简单说一下学习okhttp的理由
在builde.gradle里面添加上
compile
‘com.squareup.okhttp3:okhttp:3.4.1‘
在AndroidManifest.xml添加所需权限
<uses-permission android:name="android.permission.INTERNET" />
import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSyntaxException;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* Created by 95224 on 2016.
*/
public class OkHttpHelper {
private static OkHttpClient okHttpClient;
private Gson mGson;
private OkHttpHelper() {
okHttpClient =new OkHttpHelper.Builder().connectTimeout(10, TimeUnit.SECONDS).writeTimeout(10,TimeUnit.SECONDS)
.readTimeout(20,TimeUnit.SECONDS)
.build();
mGson = new Gson();
}
public static OkHttpHelper getInstance() {
return new OkHttpHelper();
}
public void doRequest(final Request request, final BaseCallback callback) {
callback.onRequestBrfore(request);
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
callback.onFailure(request,e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String resultStr=response.body().string();
if (callback.mType == String.class) {
callback.onSuccess(response,resultStr);
}else{
try {
Object object = mGson.fromJson(resultStr, callback.mType);
callback.onSuccess(response, object);
}catch (JsonSyntaxException e){
callback.onError(response,response.code(),e);
}catch (JsonParseException e){
callback.onError(response,response.code(),e);
}
}
}else{
callback.onError(response,response.code(),null);
}
}
});
}
public void get(String url,BaseCallback callback) {
Request request = buildRequest(url, null, HttpMethodType.GET);
doRequest(request,callback);
}
public void post(String url, Map<String, Object> params,BaseCallback callback) {
Request request =buildRequest(url,params ,HttpMethodType.POST);
doRequest(request,callback);
}
private Request buildRequest(String url, Map<String, Object> params, HttpMethodType methodType) {
Request.Builder builder = new Request.Builder();
builder.url(url);
if (methodType == HttpMethodType.GET) {
builder.get();
} else if (methodType == HttpMethodType.POST) {
RequestBody body = buildFormatData(params);
builder.post(body);
}
return builder.build();
}
private RequestBody buildFormatData(Map<String, Object> params) {
FormBody.Builder builder=new FormBody.Builder();
if (params !=null) {
for (Map.Entry<String,Object> entry : params.entrySet()){
builder.add(entry.getKey(),entry.getValue().toString());
}
}
return builder.build();
}
enum HttpMethodType{
GET,POST
}
标签:
原文地址:http://www.cnblogs.com/wgha/p/5883800.html