添加dependency
<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.1.0</version>
</dependency>
发送get请求
官方例子:https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/guide/GetExample.java
照着写了个百度的请求如下:
@Test
public void testBaidu() throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://www.baidu.com")
.build();
Response response = client.newCall(request).execute();
String respon = Objects.requireNonNull(response.body()).string();
System.out.println(respon);
}
发送带参数的get请求
加参数的方法是拼接在url中,地址和参数用“?”隔开,多个参数之间用“&”隔开。
public void testWeiboList(String uid) throws IOException {
String testUrl = WEIBO_PROFILE_URI+"?"+"uid="+uid;
System.out.println(testUrl);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(testUrl)
.build();
Response response = client.newCall(request).execute();
String respon = Objects.requireNonNull(response.body()).string();
System.out.println(respon);
}
}
发送post请求
官方例子:https://raw.githubusercontent.com/square/okhttp/master/samples/guide/src/main/java/okhttp3/guide/PostExample.java
@Test(dataProviderClass = CityDataProvider.class, dataProvider = "getdata")
public void testTerminalNum(String json, String sql) throws IOException, SQLException, ClassNotFoundException {
System.out.println("请求参数:" + json);
System.out.println("查询sql:" + sql);
//拼接网络请求
String testUrl = url + "/sample/getSample";
System.out.println("请求地址:"+testUrl);
RequestBody body = RequestBody.create(json, JSON);
Request request = new Request.Builder()
.url(testUrl)
.post(body)
.addHeader("Content-Typ", "application/json;charset=UTF-8")
.build();
Response response = client.newCall(request).execute();
String result = response.body().toString();
System.out.println("接口返回值" + result);
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(result);
JsonObject root = element.getAsJsonObject(); //获得根节点元素
int status = root.get("msg").getAsInt();
//判断status值为 1
Assert.assertEquals(status, 1)
}