OkHttp3的基本使用

6 篇文章 0 订阅


最近在使用OkHttp3和别的平台进行通信,采用json数据格式,对方平台为https协议,总结归纳如下。

同步get demo

    private final OkHttpClient client = new OkHttpClient();

    public void run() throws Exception {
        Request request = new Request.Builder()
                .url("https://publicobject.com/helloworld.txt")
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            Headers responseHeaders = response.headers();
            for (int i = 0; i < responseHeaders.size(); i++) {
                System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
            }

            System.out.println(response.body().string());
        }
    }

    public static void main(String[] args) {
        try {
            new SyncGetDemo().run();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

异步 get demo

    private final OkHttpClient client = new OkHttpClient();

    public void run() throws Exception {
        Request request = new Request.Builder()
                .url("http://publicobject.com/helloworld.txt")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override public void onResponse(Call call, Response response) throws IOException {
                try (ResponseBody responseBody = response.body()) {
                    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

                    Headers responseHeaders = response.headers();
                    for (int i = 0, size = responseHeaders.size(); i < size; i++) {
                        System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
                    }

                    System.out.println(responseBody.string());
                }
            }
        });
    }
    public static void main(String[] args) {
        try {
            new AsyncGetDemo().run();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

post json数据

    public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

    final OkHttpClient client = new OkHttpClient();

    String post(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(json, JSON);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

    public static String transUserJson(User user) {
        return com.alibaba.fastjson.JSON.toJSONString(user);
    }

    public static void main(String[] args){
        String url = "http://127.0.0.1:8088/fwzl-lock/users";
        User user = new User();
        user.setUsername("张三");
        user.setAge(35);
        user.setSex(1);
        user.setAddress("保利");
        user.setPhone("15866932566");

        try {
            String response = new OkHttpDemo().post(url, transUserJson(user));
            System.out.println(response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

post form参数

    private final OkHttpClient client = new OkHttpClient();

    public void run() throws Exception {
        RequestBody formBody = new FormBody.Builder()
                .add("username", "林则徐")
                .build();
        Request request = new Request.Builder()
                .url("http://127.0.0.1:8088/fwzl-lock/user")
                .post(formBody)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful())
                throw new IOException("Unexpected code " + response);

            System.out.println(response.body().string());
        }
    }

    public static void main(String[] args){
        try {
            new PostFormDemo().run();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

post json和form 参数的后台接口区别:

    @PostMapping("/users")
    public String users(@RequestBody User user){
    
    }
    @PostMapping("/user")
    public String user(User user){

    }

Form参数方式:Content type应该为application/x-www-form-urlencoded;charset=UTF-8

https://square.github.io/okhttp/
https://square.github.io/okhttp/recipes/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Jinwen5290

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

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

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

打赏作者

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

抵扣说明:

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

余额充值