如何在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
payloadstring has a syntax error (unclosed quotes) and doesn't actually read the content ofmyFile.json— it just references the filename - The target URL has a typo:
publisshould bepublish - You're using
APPLICATION_FORM_URLENCODEDcontent type, but we needAPPLICATION_JSONsince 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.jsonon Linux/macOS). - Content Type: Using
ContentType.APPLICATION_JSONtells 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 Exceptiondirectly. Instead, catch specific exceptions likeIOException(for file reading issues) andClientProtocolException(for HTTP request problems) to handle errors gracefully.
内容的提问来源于stack exchange,提问作者Spartacus
相关产品推荐
相关产品推荐

