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

如何在Java中发送携带JSON文件作为原始数据的POST请求(类似JMeter方式)

Fix: Send JSON File Content as POST Request Body

Got it, let's get your code working properly so you can send the actual content of myFile.json as the request body to your target URL. Your current code has a few critical issues we need to fix first:

  • Your payload string has a syntax error (unclosed quotes) and doesn't actually read the content of myFile.json — it just references the filename
  • The target URL has a typo: publis should be publish
  • You're using APPLICATION_FORM_URLENCODED content type, but we need APPLICATION_JSON since we're sending JSON data
  • No logic to read the local JSON file into the request body

Here's the corrected code that addresses all these issues:

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import java.nio.file.Files;
import java.nio.file.Paths;

public class HttpClientExample {
    public static void main(String[] args) throws Exception {
        // Read the content of myFile.json into a string
        String jsonContent = new String(Files.readAllBytes(Paths.get("myFile.json")));
        
        // Create a request entity with JSON content type
        StringEntity entity = new StringEntity(jsonContent, ContentType.APPLICATION_JSON);
        
        // Initialize HttpClient and fix the target URL typo
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost request = new HttpPost("http://1.1.1.7:80/myService/publish");
        
        // Attach the JSON entity to the POST request
        request.setEntity(entity);
        
        // Execute the request and print the status code
        HttpResponse response = httpClient.execute(request);
        System.out.println("Response Status Code: " + response.getStatusLine().getStatusCode());
    }
}

Key Details to Note:

  • Reading the JSON File: Files.readAllBytes(Paths.get("myFile.json")) reads the raw bytes of your JSON file and converts them to a string. If your file isn't in the project root directory, use a full absolute path (e.g., Paths.get("C:/Users/YourName/Documents/myFile.json") on Windows or /home/yourname/files/myFile.json on Linux/macOS).
  • Content Type: Using ContentType.APPLICATION_JSON tells the server exactly what kind of data we're sending, which is required for most JSON-based APIs to parse the request correctly.
  • Dependency Check: Make sure your project includes the Apache HttpClient library. If you're using Maven, add this to your pom.xml:
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.14</version> <!-- Use the latest stable version available -->
    </dependency>
    
  • Error Handling: In a production environment, avoid using throws Exception directly. Instead, catch specific exceptions like IOException (for file reading issues) and ClientProtocolException (for HTTP request problems) to handle errors gracefully.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 22:17:52