依赖
- <!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
- <dependency>
- <groupId>com.squareup.okhttp3</groupId>
- <artifactId>okhttp</artifactId>
- <version>3.14.9</version>
- </dependency>
示例
- package com.qzcsbj.demo;
-
- import okhttp3.*;
- import java.io.IOException;
- import java.util.concurrent.TimeUnit;
-
- /**
- * @公众号 : 全栈测试笔记
- * @博客 : www.cnblogs.com/uncleyong
- * @微信 : ren168632201
- * @描述 : <>
- */
- public class OkHttp3Test {
- public static void main(String[] args) {
- // 定义接口的URL
- String url = "http://localhost:8089/qzcsbj/user/login";
-
- // 接口的请求参数
- String requestParameter = "{\n" +
- " \"username\": \"qzcsbj\",\n" +
- " \"password\": \"123456\"\n" +
- "}";
- // 封装请求体
- MediaType mediaType = MediaType.parse("application/json");
- RequestBody requestBody = RequestBody.create(mediaType, requestParameter);
-
- // 封装请求对象
- Request request = new Request.Builder().post(requestBody)
- .addHeader("Content-Type", "application/json")
- .url(url).build();
-
- // 创建okhttp工具类
- OkHttpClient okHttpClient = new OkHttpClient.Builder()
- .connectTimeout(30, TimeUnit.SECONDS)
- .writeTimeout(30, TimeUnit.SECONDS)
- .readTimeout(30, TimeUnit.SECONDS)
- .build();
-
- try {
- // 执行这个请求对象
- Response response = okHttpClient.newCall(request).execute();
- System.out.println(response.body().string());
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
结果