OkHttp数据请求和OkHttp拦截器

来源:互联网 发布:linux 查看函数头文件 编辑:程序博客网 时间:2024/05/29 19:32


  首先,导入OkHttp的依赖包:

compile 'com.squareup.okhttp3:okhttp:3.9.0'

project的gradle中:

maven { url 'https://maven.google.com' }


OkHttp模块:

//请求数据    public void getData(final MyActivityModleListener listener){        OkHttpClient client = new OkHttpClient.Builder()                .addInterceptor(new LoggingInterceptor())                .build();        final Request request = new Request.Builder().url("http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.billboard.billList&type=1&size=10&offset=0").build();        client.newCall(request).enqueue(new Callback() {            @Override            public void onFailure(Call call, IOException e) {                // 1 网络                listener.onfailed(1);            }            @Override            public void onResponse(Call call, Response response) throws IOException {                String result = response.body().string();                Gson gson = new Gson();                MyBean myBean = gson.fromJson(result, MyBean.class);                listener.success(myBean);            }        });

OkHttp拦截器:

import android.os.Build;import java.io.IOException;import okhttp3.Interceptor;import okhttp3.Request;import okhttp3.Response;/** * 网络拦截器 */public class LoggingInterceptor implements Interceptor {    private static final String UA = "User-Agent";    @Override    public Response intercept(Chain chain) throws IOException {        Request request = chain.request()                .newBuilder()                .addHeader(UA, makeUA())                .build();        return chain.proceed(request);    }    private String makeUA() {        String s = Build.BRAND + "/" + Build.MODEL + "/" + Build.VERSION.RELEASE;        return Build.BRAND + "/" + Build.MODEL + "/" + Build.VERSION.RELEASE;    }}





原创粉丝点击