如何使用 HttpURLConnection 在请求正文中发送数据?

我正在使用向本地部署并使用JAVA Spark创建的本地服务发出POST请求。我想在使用 HttpURLConnection 进行 POST 调用时在请求正文中发送一些数据,但每次 JAVA Spark 中的请求正文都为空。以下是我用于此目的的代码HttpURLConnection

Java Spark POST Service Handler

post("/", (req, res) -> {
    System.out.println("Request Body: " + req.body());
    return "Hello!!!!";
});

进行 POST 调用的 HTTPClass

public class HTTPClassExample{
    public static void main(String[] args) {
        try{
            URL url = new URL("http://localhost:4567/");
            HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
            httpCon.setDoOutput(true);
            httpCon.setRequestMethod("POST");
            httpCon.connect();
            OutputStream os = httpCon.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");    
            osw.write("Just Some Text");
            System.out.println(httpCon.getResponseCode());
            System.out.println(httpCon.getResponseMessage());
            osw.flush();
            osw.close();  
        } catch(Exception ex){
            ex.printStackTrace();
        }
    }
}

答案 1

您应该仅在正文中写入参数之后调用,而不是在此之前调用。您的代码应如下所示:httpCon.connect();

URL url = new URL("http://localhost:4567/");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");
OutputStream os = httpCon.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");    
osw.write("Just Some Text");
osw.flush();
osw.close();
os.close();  //don't forget to close the OutputStream
httpCon.connect();

//read the inputstream and print it
String result;
BufferedInputStream bis = new BufferedInputStream(httpCon.getInputStream());
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result2 = bis.read();
while(result2 != -1) {
    buf.write((byte) result2);
    result2 = bis.read();
}
result = buf.toString();
System.out.println(result);

答案 2

我以XML格式发布了请求的数据,代码如下所示。还应添加请求属性“接受”和“内容类型”。

URL url = new URL("....");
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();

httpConnection.setRequestMethod("POST");
httpConnection.setRequestProperty("Accept", "application/xml");
httpConnection.setRequestProperty("Content-Type", "application/xml");

httpConnection.setDoOutput(true);
OutputStream outStream = httpConnection.getOutputStream();
OutputStreamWriter outStreamWriter = new OutputStreamWriter(outStream, "UTF-8");
outStreamWriter.write(requestedXml);
outStreamWriter.flush();
outStreamWriter.close();
outStream.close();

System.out.println(httpConnection.getResponseCode());
System.out.println(httpConnection.getResponseMessage());

InputStream xml = httpConnection.getInputStream();

推荐