之前一直用Hutool,早就忘记OkHttp这个牛逼的工具了,因为担心公司整体业务使用OkHttp,于是将原Hutool代码修改为OkHttp。

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

入门Demo Get无参数

    /**
     * 1、创建客户端
     * 2、创建请求
     * 3、客户端执行请求
     * 4、处理结果
     */
    @Test
    public void openHttpTestDemo1() {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("Https://www.baidu.com")
                .get()  // 默认是get请求
                .build();
        try (Response response = client.newCall(request).execute()) {
            System.out.println(response.body().string());
        } catch (IOException e) {
            throw new RuntimeException("OkHttp请求&处理:异常", e);
        }
    }

Get带参数

Post

Post常规Json参数(已通过测验)

            Map<String, Object> params = new HashMap<>();
            params.put("template_id", templateId);
            String formJson = JSONObject.toJSONString(params);
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url((SEND_MESSAGE_URL + token).trim())
                    .post(RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), formJson))  // 默认是get请求
                    .build();
                Response response = client.newCall(request).execute();
                JSONObject jsonObject = JSONObject.parseObject(response.body().string());

Post Json参数。请求Body格式:x-www-form-urlencoded (不支持文件上传)

        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "param1=01&param2=02");
        Request request = new Request.Builder()
                .url("https://www.baidu.com")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = client.newCall(request).execute();

Post 表单参数。请求Body格式:form-data (带有文件上传)

        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("param1","1")
                .addFormDataPart("param2","IMG_0001.png",
                        RequestBody.create(MediaType.parse("application/octet-stream"),
                                new File("/Users/zanglikun/Desktop/IMG_0001.png")))
                .build();
        Request request = new Request.Builder()
                .url("https://www.baidu.com")
                .method("POST", body)
                .build();
        Response response = client.newCall(request).execute();

Post 表单参数。请求以表单形式(已测试)

        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("clientId",clientId)
                .addFormDataPart("secret",secret)
                .build();
        Request request = new Request.Builder()
                .url((TEST_DOMAIN + GENERATE_ACCESSTOKEN_URL).trim())
                .post(body)
                .build();
        Response response = null;
      
        response = client.newCall(request).execute();

如果你不想写OkHttp的代码,记得PostMan可以生成Java代码:https://www.zanglikun.com/12877.html

特殊说明:
上述文章均是作者实际操作后产出。烦请各位,请勿直接盗用!转载记得标注原文链接:www.zanglikun.com
第三方平台不会及时更新本文最新内容。如果发现本文资料不全,可访问本人的Java博客搜索:标题关键字。以获取最新全部资料 ❤