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

如何使用HttpUrlConnection发送带JSON参数的POST请求?需匹配指定结构

Using HttpURLConnection to Send Your Target POST Request

Got it, let's break down how to send exactly the POST request you described using Java's HttpURLConnection. I'll share a complete, ready-to-use code example with explanations for each key part.

Step-by-Step Implementation

First, here's the full code snippet tailored to your requirements:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class JsonPostRequestExample {
    public static void main(String[] args) {
        // Replace these placeholders with your actual values
        String parserApiUrl = "YOUR_PARSER_API_ENDPOINT";
        String s3BaseUrl = "YOUR_S3_BASE_URL";
        String imageKey = "YOUR_IMAGE_KEY";
        String apiKey = "sdsdasdwdw";

        // Build the JSON request body matching your specified structure
        String jsonRequestBody = String.format(
            "{\"method\": \"post\", \"url\": \"%s\", \"data\": { \"url\": \"%s\" }, \"headers\": { \"x-api-key\": \"%s\" }}",
            parserApiUrl,
            s3BaseUrl + imageKey,
            apiKey
        );

        try {
            // Initialize connection to the target API
            URL targetUrl = new URL(parserApiUrl);
            HttpURLConnection connection = (HttpURLConnection) targetUrl.openConnection();

            // Configure connection for POST request
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("x-api-key", apiKey); // Add required API key header
            connection.setDoOutput(true); // Enable output stream to send POST data

            // Write JSON body to the request stream
            try (OutputStream outputStream = connection.getOutputStream()) {
                byte[] jsonBytes = jsonRequestBody.getBytes("utf-8");
                outputStream.write(jsonBytes, 0, jsonBytes.length);
            }

            // Read and print the server's response
            try (BufferedReader responseReader = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), "utf-8"))) {
                StringBuilder responseBuilder = new StringBuilder();
                String line;
                while ((line = responseReader.readLine()) != null) {
                    responseBuilder.append(line.trim());
                }
                System.out.println("Server Response: " + responseBuilder.toString());
            }

        } catch (IOException e) {
            e.printStackTrace();
            // Add custom exception handling here for your application
        }
    }
}

Key Details to Keep in Mind

  • Connection Setup: We set setRequestMethod("POST") to define the HTTP method, and setDoOutput(true) to allow sending data in the request body (required for POST).
  • Headers: The Content-Type: application/json header tells the server we're sending JSON-formatted data, and we explicitly include the x-api-key header as your request requires.
  • JSON Construction: We use String.format to inject dynamic values into the JSON structure. For more complex JSON scenarios, consider using a library like Jackson or Gson to serialize objects (avoids manual syntax errors).
  • Resource Management: Try-with-resources blocks automatically close streams and connections, preventing resource leaks in your code.

Optional Improvements for Production

  • Use a JSON library for safer serialization (example with Jackson):
    // Add Jackson dependency first, then use ObjectMapper
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> requestPayload = new HashMap<>();
    requestPayload.put("method", "post");
    requestPayload.put("url", parserApiUrl);
    
    Map<String, String> data = new HashMap<>();
    data.put("url", s3BaseUrl + imageKey);
    requestPayload.put("data", data);
    
    Map<String, String> headers = new HashMap<>();
    headers.put("x-api-key", apiKey);
    requestPayload.put("headers", headers);
    
    String jsonRequestBody = mapper.writeValueAsString(requestPayload);
    
  • Add checks for non-2xx HTTP status codes (use connection.getResponseCode() and read the error stream if the code is not successful).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:04:02