我正在使用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();
}
}
}
getOutputStream
会在内部调用connect
。如果您想显式连接,请在getOutputStream
之前调用connect
。为了测试自己,禁用互联网并且当连接失败时,您将看到getOutputStream
调用了失败的connect
。 - NateS