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

26

我正在使用HttpURLConnection向本地部署并使用JAVA Spark创建的服务发起POST请求。 我希望在使用HttpURLConnection进行POST调用时在请求体中发送一些数据,但每次在JAVA Spark中的请求体都是null。以下是我使用的代码

JAVA Spark POST服务处理程序

JAVA Spark POST服务处理程序

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

HTTPClass 发起 POST 请求

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();
        }
    }
}
2个回答

38

您应该在将参数写入请求体后再调用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
看起来这不是真的。调用 getOutputStream 会在内部调用 connect。如果您想显式连接,请在 getOutputStream 之前调用 connect。为了测试自己,禁用互联网并且当连接失败时,您将看到 getOutputStream 调用了失败的 connect - NateS

7

我已经以XML格式发布了请求数据,代码如下。您应该添加请求属性Accept和Content-Type。

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();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接