Java POST请求体被识别为NULL引发500错误求助
Hey there, let's work through this issue together. Your problem is clear: when sending a POST request with SKU data from your Java code, the server returns a 500 error saying the request body is NULL, but the same request works perfectly in Postman. Let's break down the root causes and fix them step by step.
Key Issues in Your Current Code
1. Missing Critical Request Headers
Postman automatically sets proper Content-Type and Accept headers when sending JSON data, but your code has these essential lines commented out:
// connection.setRequestProperty("Content-Type", "application/json; utf-8"); // connection.setRequestProperty("Accept", "application/json");
Without these headers, the server has no way to recognize that you're sending JSON content. It can't parse the request body as a result—hence the "NULL body" error.
2. Incorrect Request Setup Order
You're writing to the output stream before configuring request headers and timeouts. Once you call connection.getOutputStream(), the HTTP connection is initialized, and any subsequent changes to request properties (like headers or timeouts) won't take effect. This means even if you uncommented the headers later, they were never actually being sent to the server.
Corrected Code
Here's the fixed version of your code with comments highlighting the key changes:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; public class PricingAPI { private static HttpURLConnection connection; public static void main(String[] args) { BufferedReader readsFromURL; String lineFromURL; StringBuffer responseContent = new StringBuffer(); String skuStartAfter = "0"; List<String> jsonInputStringList; String jsonInputString; Path skuList = FileSystems.getDefault().getPath("SKU.json"); try { jsonInputStringList = Files.readAllLines(skuList); jsonInputString = String.join("", jsonInputStringList); System.out.println(jsonInputString); URL url = new URL("https://emerson-api.emersonecologics.com/pricing/v1/pricing-request/?limit=100&startAfterId=" + skuStartAfter + "&endsWithId="); connection = (HttpURLConnection) url.openConnection(); // --- REORDERED: Configure request BEFORE opening output stream --- // Set request method and enable output connection.setRequestMethod("POST"); connection.setDoOutput(true); // Add critical headers (uncommented and moved here) connection.setRequestProperty("Content-Type", "application/json; utf-8"); connection.setRequestProperty("Accept", "application/json"); // Set timeouts BEFORE writing to stream connection.setConnectTimeout(5000); connection.setReadTimeout(5000); // Now write the request body OutputStream os = connection.getOutputStream(); byte [] input = jsonInputString.getBytes("utf-8"); os.write(input, 0, input.length); os.flush(); // Ensure all JSON data is sent to the server os.close(); // Handle response if (connection.getResponseCode() > 299) { readsFromURL = new BufferedReader(new InputStreamReader(connection.getErrorStream())); while ((lineFromURL = readsFromURL.readLine()) != null) { responseContent.append(lineFromURL); } readsFromURL.close(); System.out.println("Error Response: " + responseContent); System.out.println("Response Code: " + connection.getResponseCode()); } else { readsFromURL = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((lineFromURL = readsFromURL.readLine()) != null) { responseContent.append(lineFromURL.substring(163,lineFromURL.length()-52)); } System.out.println("Success Response: " + responseContent); readsFromURL.close(); } }catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // Always disconnect to free resources if (connection != null) { connection.disconnect(); } } } }
Key Changes Made:
- Uncommented and moved the
Content-TypeandAcceptheaders to before opening the output stream so they're actually sent - Reordered all request configuration (method, headers, timeouts) to happen before writing the request body
- Added
os.flush()andos.close()to ensure all JSON data is transmitted to the server - Added a
finallyblock to disconnect the connection and clean up resources properly
Next Steps for Batch Processing 6000+ SKUs
Once the single request works, you can implement batch processing for your full SKU list:
- Split your complete SKU list into chunks of 100 items (matching the API's limit)
- Loop through each chunk, sending a separate POST request for each group
- Use the
startAfterIdparameter to handle pagination—check the API's response for the last ID in each batch to use as the nextstartAfterId - Add error handling for failed requests (e.g., retry logic, logging failed batches for later reprocessing)
内容的提问来源于stack exchange,提问作者Andrew Werling

