OKhttp3 简单使用

概述

okhttp 官网:https://square.github.io/okhttp/

HTTP是现代应用网络的方式。这就是我们交换数据和媒体的方式。有效地执行HTTP可以加快您的负载并节省带宽。

OkHttp是一个默认有效的HTTP客户端:

  • HTTP / 2支持允许对同一主机的所有请求共享套接字。
  • 连接池减少了请求延迟(如果HTTP / 2不可用)。
  • 透明GZIP缩小了下载大小。
  • 响应缓存完全避免网络重复请求。
    当网络很麻烦时,OkHttp坚持不懈:它将从常见的连接问题中无声地恢复。如果您的服务有多个IP地址,如果第一次连接失败,OkHttp将尝试备用地址。这对于IPv4 + IPv6和冗余数据中心中托管的服务是必需的。OkHttp启动具有现代TLS功能(SNI,ALPN)的新连接,并在握手失败时回退到TLS 1.0。

使用OkHttp很简单。它的请求/响应API采用流畅的构建器和不变性设计。它支持同步阻塞调用和带回调的异步调用。

本文只是简单的试用一下,两个小demo。

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.11.0</version>
</dependency>

get请求

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

public class GetExample {
    OkHttpClient client = new OkHttpClient();//创建okhttp客户端

    String run(String url) throws IOException {
    	//创建request
        Request request = new Request.Builder()
                .url(url)
                .build();
		//同步执行请求
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();//返回响应
        }
    }

    public static void main(String[] args) throws IOException {
        GetExample example = new GetExample();
        String response = example.run("https://raw.github.com/square/okhttp/master/README.md");
        System.out.println(response);
    }
}

post请求

import okhttp3.*;

import java.io.IOException;

public class PostExample {
//指定请求头,json格式
    public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

    OkHttpClient client = new OkHttpClient();

    String post(String url, String json) throws IOException {
    //创建请求体
        RequestBody body = RequestBody.create(JSON, json);
        //创建requestbody
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
                //同步执行请求
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

//拼接json格式参数
    String bowlingJson(String player1, String player2) {
        return "{'winCondition':'HIGH_SCORE',"
                + "'name':'Bowling',"
                + "'round':4,"
                + "'lastSaved':1367702411696,"
                + "'dateStarted':1367702378785,"
                + "'players':["
                + "{'name':'" + player1 + "','history':[10,8,6,7,8],'color':-13388315,'total':39},"
                + "{'name':'" + player2 + "','history':[6,10,5,10,10],'color':-48060,'total':41}"
                + "]}";
    }

    public static void main(String[] args) throws IOException {
        PostExample example = new PostExample();
        String json = example.bowlingJson("Jesse", "Jake");
        String response = example.post("http://www.roundsapp.com/post", json);
        System.out.println(response);
    }
}

同步/异步请求

上面两个实例都是同步请求,下面看看异步请求如何编写:

//异步请求
Call call = client.newCall(request);
call.enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        System.out.println(e.getMessage());
    }

    @Override
    public void onResponse(Call call, okhttp3.Response response) throws IOException {
        String string = response.body().string();
        System.out.println(string);
    }
});
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

快乐崇拜234

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值