You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中使用HttpClient向REST API发送指定JSON格式POST请求的参数填充方案

Hey there! Let's get your Java HttpClient code working to send that required JSON POST request. The main piece you're missing is attaching the JSON request body to your POST call—right now your request doesn't include any body, which is why it won't match what the API expects.

Here's how to fix it step by step:

  1. Create your JSON request body
    First, build the JSON string that matches the format the API requires. You can hardcode it for starters (just replace "your-id-here" with your actual string value):

    {"_id": "your-id-here", "minDuration": 0, "maxDuration": 0, "calculatedMaxLimitDuration": 0}
    
  2. Attach the body to your POST request
    Java's HttpRequest.Builder.POST() method needs a HttpRequest.BodyPublisher to send the body data. We'll use BodyPublishers.ofString() to turn our JSON string into a usable publisher. Also, don't forget to add the Content-Type: application/json header—this tells the API that you're sending JSON data, which is usually required for JSON request bodies.

  3. Updated full code
    Here's your modified code with all the necessary changes:

    import java.net.URI;
    import java.net.http.HttpClient;
    import java.net.http.HttpRequest;
    import java.net.http.HttpResponse;
    import java.io.IOException;
    
    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 {
            // Build the JSON request body as a string
            String requestBody = "{\"_id\": \"your-id-here\", \"minDuration\": 0, \"maxDuration\": 0, \"calculatedMaxLimitDuration\": 0}";
            
            HttpClient client = HttpClient.newHttpClient();
            HttpRequest request = HttpRequest.newBuilder()
                // Pass the request body to the POST method
                .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                .header("accept", "application/json")
                // Critical: Tell the server we're sending JSON
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer secret")
                .uri(URI.create(POSTS_API_URL))
                .build();
            
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            // Print status code to debug success/errors
            System.out.println("Response Status Code: " + response.statusCode());
            System.out.println(response.body());
        }
    }
    

A better approach for complex data (optional)

If you end up needing to work with more complex JSON structures later, manually writing JSON strings can get error-prone. A cleaner way is to use a library like Jackson to serialize a Java object into JSON. Here's a quick example:

First, create a simple class that mirrors your JSON structure:

public class TimeUpdateRequest {
    private String _id;
    private int minDuration;
    private int maxDuration;
    private int calculatedMaxLimitDuration;

    // Constructor
    public TimeUpdateRequest(String _id, int minDuration, int maxDuration, int calculatedMaxLimitDuration) {
        this._id = _id;
        this.minDuration = minDuration;
        this.maxDuration = maxDuration;
        this.calculatedMaxLimitDuration = calculatedMaxLimitDuration;
    }

    // Getters and setters (required for Jackson to serialize the object)
    public String getId() { return _id; }
    public void setId(String _id) { this._id = _id; }
    public int getMinDuration() { return minDuration; }
    public void setMinDuration(int minDuration) { this.minDuration = minDuration; }
    public int getMaxDuration() { return maxDuration; }
    public void setMaxDuration(int maxDuration) { this.maxDuration = maxDuration; }
    public int getCalculatedMaxLimitDuration() { return calculatedMaxLimitDuration; }
    public void setCalculatedMaxLimitDuration(int calculatedMaxLimitDuration) { this.calculatedMaxLimitDuration = calculatedMaxLimitDuration; }
}

Then use Jackson's ObjectMapper to convert the object to JSON:

import com.fasterxml.jackson.databind.ObjectMapper;

// Inside your main method...
ObjectMapper objectMapper = new ObjectMapper();
TimeUpdateRequest requestObject = new TimeUpdateRequest("your-id-here", 0, 0, 0);
String requestBody = objectMapper.writeValueAsString(requestObject);

This way, you can work with Java objects instead of raw strings, which is easier to maintain.

内容的提问来源于stack exchange,提问作者liloso

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 06:47:29