使用OkHttp的那些事儿(四)

本篇继续介绍关于OkHttp的其他使用姿势。

1.OkHttp结合gson使用:其中ResponseBody.charStream()使用Content-Type响应头来选择在解码响应正文时要使用的字符集。 如果没有指定字符集,它默认为UTF-8。

 private void Test5() throws IOException {
        OkHttpClient client = new OkHttpClient();

        Gson gson = new Gson();

        Request request = new Request.Builder().url("https://api.github.com/gists/c2a7c39532239ff261be").build();

        Response response = client.newCall(request).execute();

        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

        Git git = gson.fromJson(response.body().charStream(), Git.class);

        for (Map.Entry<String, GitFile> entry : git.files.entrySet()){
            System.out.println(entry.getKey());
            System.out.println(entry.getValue().content);
        }
    }

    class Git {
        Map<String, GitFile> files;
    }
    class GitFile {
        String content;
    }

2.拦截器的使用:
okHttp中注册的拦截器可以分成两类,分别是程序拦截器和网络拦截器。两者最大的不同就是程序拦截器只会对网络请求调用一次,然后拦截器返回的数据会直接从缓存中读取;而网络拦截器会进行两次的网络请求。
首先是注册程序拦截器:

/**
 * Created by BeautifulSoup on 2017/3/1.
 * 记录日志拦截器
 */
public class AddLogInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request=chain.request();
        long startTime=System.nanoTime();

        Log.i("AddLogInterceptor:",String.format("Sending request %s on %s%n%s",
                request.url(), chain.connection(), request.headers()));

        Response response=chain.proceed(request);//放行

        long endTime=System.nanoTime();

        Log.i("AddLogInterceptor","请求的时间是:"+(endTime-startTime)/1e6d+",响应的连接是:"+response.request().url()+",响应头是:"+response.headers());
        return response;
    }
}
              private static final MediaType MEDIA_TYPE_MAKEDOWN=MediaType.parse("text/x-markdown;charset=UTF-8");

              OkHttpClient client3=builder.addInterceptor(new AddLogInterceptor()).build();

                //使用POST提交请求,参数封装在请求体中
                String postBody = ""
                        + "Releases\n"
                        + "--------\n"
                        + "\n"
                        + " * _1.0_ May 6, 2017\n"
                        + " * _1.1_ June 15, 2017\n"
                        + " * _1.2_ August 11, 2017\n";
                Request request3=new Request.Builder().url("https://api.github.com/markdown/raw")
                        .post(RequestBody.create(MEDIA_TYPE_MAKEDOWN,postBody))
                        .build();
                client3.newCall(request3).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        System.out.println(response.body().string());
                    }
                });

网络拦截器的注册和程序拦截器的注册基本一致,唯一不同之处:

OkHttpClient client3=builder.addNetworkInterceptor(new AddLogInterceptor()).build();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中使用OkHttp主要是为了发送HTTP请求和处理响应。OkHttp是一个高效、易用的HTTP客户端库,它具有简洁的API和强大的功能。你可以使用OkHttp来发送GET、POST、PUT和DELETE等HTTP请求,并处理响应的数据。 首先,你需要在你的Spring Boot项目中添加OkHttp的依赖。你可以在你的pom.xml文件中添加以下代码来引入OkHttp依赖: ```xml <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.14.9</version> </dependency> ``` 接下来,在你的Spring Boot应用程序的代码中,你可以创建一个OkHttpClient对象,用于发送HTTP请求。你可以使用以下代码示例来创建一个OkHttpClient对象: ```java OkHttpClient client = new OkHttpClient(); ``` 然后,你可以使用OkHttpClient对象发送HTTP请求。例如,发送一个GET请求并获取响应的示例代码如下: ```java Request request = new Request.Builder() .url("https://api.example.com/data") .build(); try (Response response = client.newCall(request).execute()) { String responseData = response.body().string(); // 处理响应数据 } catch (IOException e) { // 处理异常 } ``` 在这个例子中,我们创建了一个GET请求,并指定了请求的URL。然后,使用client.newCall(request).execute()方法发送请求并获取响应。最后,我们可以通过response.body().string()方法获取响应的数据。 除了发送GET请求,你还可以使用OkHttpClient发送其他类型的请求,比如POST、PUT和DELETE等。你可以根据具体的需求来设置请求的URL、请求头、请求体等。 这样,你就可以在Spring Boot中使用OkHttp来发送HTTP请求了。通过使用OkHttp,你可以轻松地与外部API进行交互,并处理响应的数据。希望这个回答对你有帮助!<span class="em">1</span>

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值