如何使用 HttpURLConnection 在请求正文中发送数据?
2022-09-01 18:49:33
我正在使用向本地部署并使用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();
}
}
}