引入依赖
compile 'com.squareup.okhttp3:okhttp:3.9.0'
OkHttpUtils
public class OkHttpUtils {
private static final OkHttpClient CLIENT = new OkHttpClient();
/**
* get请求.
* @param url
* @param callback
* */
public static void get(String url, OkHttpCallback callback) {
callback.url = url;
Request request = new Request.Builder().url(url).build();
CLIENT.newCall(request).enqueue(callback);
}
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
/**
* post请求.
* */
public static void post(String url, String json, OkHttpCallback callback) {
callback.url = url;
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder().url(url).post(body).build();
CLIENT.newCall(request).enqueue(callback);
}
/**
*
* */
public static void downFile(String url,final String saveDir, OkHttpCallback callback) {
callback.url = url;
Request request = new Request.Builder().url(url).build();
CLIENT.newCall(request).enqueue(callback);
}
}
OkHttpCallback
public class OkHttpCallback implements Callback {
private final String TAG = OkHttpCallback.class.getSimpleName();
public String url;
public String result;
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d(TAG, "url: " + url);
result = response.body().string().toString();
Log.d(TAG, "请求成功: " + result);
onFinish("success", result);
}
@Override
public void onFailure(Call call, IOException e) {
Log.d(TAG, "url: " + url);
Log.d(TAG, "请求失败:" + e.toString());
onFinish("failure", e.toString());
}
public void onFinish(String status, String msg) {
Log.d(TAG, "url: " + url + " status:" + status);
}
}
调用示例
OkHttpUtils.get(url, new OkHttpCallback(){
@Override
public void onResponse(Call call, Response response) throws IOException {
super.onResponse(call, response);
Logger.i(result);
}
@Override
public void onFailure(Call call, IOException e) {
super.onFailure(call, e);
Logger.i(e.getMessage());
}
@Override
public void onFinish(String status, String msg) {
super.onFinish(status, msg);
}
});