【问题标题】:how do i use the httpClient POST in java我如何在 java 中使用 httpClient POST
【发布时间】: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"=&gt;"35", "Ben"=&gt;"37", "Joe"=&gt;"43") 这样的关联数组,然后将其转换为 Json 字符串

标签: java arrays http post


【解决方案1】:

我建议你使用RestTemplate 或WebClient 来调用API,会很简单!

如下所示的sn-p

{
      HttpHeaders headers = new HttpHeaders();
      headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
      HttpEntity <String> entity = new HttpEntity<String>(headers);
      
      return restTemplate.exchange("
         http://serviceToCall:8080/endPoint", HttpMethod.POST, entity, String.class).getBody();
   }

在此处阅读有关 restTemplate 的更多信息 https://www.tutorialspoint.com/spring_boot/spring_boot_rest_template.htm

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多