发起HTTP请求:使用OkHttpClient
现在java比较好用的http客户端是开源的OkHttp。支持HTTP/2, 简单易用且灵活。
官网:https://square.github.io/okhttp/
简单使用测试(http、https类型的get,post):
class OkHttpClientUtilTest {
@Test
public void doGet() throws IOException {
String url = "http://httpbin.org/anything";
new OkHttpClient();
OkHttpClient client = Request request = new Request.Builder()
url(url)
.build();
.try (Response response = client.newCall(request).execute()) {
String res = response.body().string();
System.out.println(res);
}
new Request.Builder()
request = get()
.url(url + "?key1=value1&key2=value2").header("Cookie", "cook1=sd;cook2=sdd;").build();
.try (Response response = client.newCall(request).execute()) {
String res = response.body().string();
System.out.println(res);
}
"https://httpbin.org/anything";
url = new Request.Builder()
request = url(url)
.build();
.try (Response response = client.newCall(request).execute()) {
String res = response.body().string();
System.out.println(res);
}
}
@Test
public void doPost() throws IOException {
new OkHttpClient();
OkHttpClient client =
String url = "http://httpbin.org/anything";
new JsonMapper();
JsonMapper mapper = createObjectNode();
ObjectNode node = mapper.put("key1", "value1");
node.put("key2", "value2");
node.String jsonStr = node.toString();
create(jsonStr, MediaType.get("application/json; charset=utf-8"));
RequestBody body = RequestBody.Request request = new Request.Builder()
url(url)
.post(body)
.build();
.try (Response response = client.newCall(request).execute()) {
String res = response.body().string();
System.out.println(res);
}
"https://httpbin.org/anything";
url = new Request.Builder()
request = url(url)
.post(body)
.build();
.try (Response response = client.newCall(request).execute()) {
String res = response.body().string();
System.out.println(res);
}
} }
更详细的用法还是要参考官网的文档。
发表回复