java中post请求entity为空时报错
当在Java中进行POST请求时,如果请求体为空,那么可以使用以下两种方法来避免出现异常:
- 不设置请求体
如果请求体为空,那么可以不设置请求体,直接发送POST请求。示例代码如下:
URL url = new URL("http://example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
int status = con.getResponseCode();
- 设置空请求体
可以设置一个空的请求体,示例代码如下:
URL url = new URL("http://example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(new byte[]{});
int status = con.getResponseCode();
需要注意的是,如果请求体为空,那么需要设置setDoOutput(true),否则会出现异常
原文地址: https://www.cveoy.top/t/topic/huar 著作权归作者所有。请勿转载和采集!