框架

本文介绍了一个使用OkHttp进行网络请求的实用工具类实现,包括如何设置拦截器记录HTTP日志,发起GET请求并解析返回的数据。同时,还展示了如何通过Gson库将JSON字符串转换为Java对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package net.com.exam;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.google.gson.Gson;

import java.io.IOException;

import bean.com.exam.ItemBean;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * Created by pc on 2017/10/17.
 */

public class OkhttpUtils {

    private static OkhttpUtils okhttpUtils;
    private OkHttpClient okHttpClient;
    private Handler handler = new Handler(Looper.getMainLooper());

    public OkhttpUtils(){
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .build();

    }

    //单例模式
    public static OkhttpUtils getInstance(){
        if(okhttpUtils==null){
            synchronized (OkhttpUtils.class){
                if(okhttpUtils==null){
                    okhttpUtils = new OkhttpUtils();
                }
            }
        }
        return okhttpUtils;
    }

    public void doGet(String url, final Class clazz, final OnNetListener onNetListener){

        Request request = new Request.Builder()
                .url(url)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Log.e("TAG-------",string);
                final ItemBean itemBean = (ItemBean) new Gson().fromJson(string,clazz);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        onNetListener.onSuccess(itemBean);
                    }
                });
            }
        });

    }

}

package net.com.exam;

import bean.com.exam.ItemBean;

/**
 * Created by pc on 2017/10/17.
 */

public interface OnNetListener {

    public void onSuccess(ItemBean itemBean);

}

compile 'com.squareup.okhttp3:okhttp:3.9.0'
compile 'com.google.code.gson:gson:2.8.2'
compile 'com.squareup.okhttp3:logging-interceptor:3.9.0'
compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值