【发布时间】:2021-12-29 22:46:05
【问题描述】:
我正在尝试将 http 发布到我需要发布内容的 rest api
{
"_id": "string",
"minDuration": 0,
"maxDuration": 0,
"calculatedMaxLimitDuration": 0,
}
但我不太了解 java 和数组(我猜),因为我使用 php 并且多年来没有编码,所以我应该在 .POST() 中放入什么???
public class App {
static String lockId = "secret";
private static final String POSTS_API_URL = "Url" + lockId + "/update-time";
public static void main( String[] args ) throws IOException, InterruptedException {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.POST()
.header("accept", "application/json")
.header("Authorization", "Bearer secret")
.uri(URI.create(POSTS_API_URL))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
}
}
【问题讨论】:
-
只需将该 json 创建为字符串并将其放入请求的正文中。
-
你需要使用
.POST(BodyPublishers.ofString(yourJsonString)) -
@f1sh 有没有办法将数组放入 Json 字符串?就像在 php 中一样,我可以创建一个像
array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43")这样的关联数组,然后将其转换为 Json 字符串