用Intelij Idea创建java项目,如下图:

添加阿里云镜像:
groovy
maven { url 'https://maven.aliyun.com/repository/public/' }
添加Okhttp依赖:
groovy
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
java代码如下:
java
package org.example;
import java.io.IOException;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import okhttp3.*;
public class PostExample {
public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
final OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(json, JSON);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
String bowlingJson(String player1, String player2) {
return "{\"winCondition\":\"HIGH_SCORE\","
+ "\"name\":\"Bowling\","
+ "\"round\":4,"
+ "\"lastSaved\":1367702411696,"
+ "\"dateStarted\":1367702378785,"
+ "\"players\":["
+ "{\"name\":\"" + player1 + "\",\"history\":[10,8,6,7,8],\"color\":-13388315,\"total\":39},"
+ "{\"name\":\"" + player2 + "\",\"history\":[6,10,5,10,10],\"color\":-48060,\"total\":41}"
+ "]}";
}
public static void main(String[] args) throws IOException {
PostExample example = new PostExample();
String json = example.bowlingJson("Jesse", "Jake");
String response = example.post("https://jsonplaceholder.typicode.com/posts", json);
System.out.println(response);
}
}
执行结果:
{
"winCondition": "HIGH_SCORE",
"name": "Bowling",
"round": 4,
"lastSaved": 1367702411696,
"dateStarted": 1367702378785,
"players": [
{
"name": "Jesse",
"history": [
10,
8,
6,
7,
8
],
"color": -13388315,
"total": 39
},
{
"name": "Jake",
"history": [
6,
10,
5,
10,
10
],
"color": -48060,
"total": 41
}
],
"id": 101
}