这是一篇很水的文章,纯粹为了记录一些代码。
Google HTTP Client Library for Java 和 OkHttpClient 是两个很流行的http client JAVA库。
下面来看看用它们分别怎样通过POST请求把JSON数据发送到服务器。
JDK版本:1.8.0_221
➤ Google HTTP Client
public String performHttpPost(String url, String payload, Map<String, String> headers) {
HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
HttpRequest request;
try {
byte[] contentBytes = payload.getBytes(Charsets.UTF_8);
HttpContent content = new ByteArrayContent("application/json", contentBytes);
request = requestFactory.buildPostRequest(new GenericUrl(url), content);
if (MapUtils.isNotEmpty(headers)) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
request.getHeaders().set(entry.getKey(), entry.getValue());
}
}
return request.execute().parseAsString();
} catch (IOException e) {
log.error("failed to send POST request", e);
}
}
其中,payLoad是你要发送的JSON数据字符串,headers是要设置到请求头中的key-value对。
文章来源:https://www.codelast.com/
➤ OkHttpClient
public String performHttpPost(String url, String payload) {
HttpUrl.Builder builder = null;
try {
HttpUrl httpUrl = HttpUrl.parse(url);
if (httpUrl != null) {
builder = httpUrl.newBuilder();
}
} catch (IllegalArgumentException e) {
log.error("failed to create HttpUrl.Builder from url: {}", url, e);
}
if (builder == null) {
return null;
}
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), payload);
Request request = new Request.Builder()
.url(builder.build())
.post(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
ResponseBody body = response.body();
if (body == null) {
log.error("null response body");
return null;
}
return body.string();
} catch (IOException e) {
log.error("failed to send POST request", e);
}
return null;
}
其中,payLoad是你要发送的JSON数据字符串。
文章来源:https://www.codelast.com/
➤➤ 版权声明 ➤➤
转载需注明出处:codelast.com
感谢关注我的微信公众号(微信扫一扫):
以及我的微信视频号: