Android集成okhttp

引入依赖

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);
    }
});
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值