我正在使用 HttpURLConnection
向本地部署并使用 JAVA Spark 创建的本地服务发出 POST 请求。 当我使用 HttpURLConnection
进行 POST 调用时,我想在请求正文中发送一些数据,但每次 JAVA Spark 中的请求正文为 null 时。 下面是我的代码用于此
Java Spark POST 服务处理程序
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();
}
}
}
最佳答案
您应该仅在将参数写入正文之后而不是之前调用 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);
关于java - 如何使用 HttpURLConnection 在请求正文中发送数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44305351/