java的借口调用HttpURLConnection设置请求参数
时间: 2023-10-12 18:22:32 浏览: 84
可以通过以下代码来设置HttpURLConnection的请求参数:
```
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
// 设置请求体
String requestBody = "{\"key1\":\"value1\", \"key2\":\"value2\"}";
OutputStream outputStream = conn.getOutputStream();
outputStream.write(requestBody.getBytes());
outputStream.flush();
outputStream.close();
```
其中setRequestMethod()设置请求方法,setConnectTimeout()和setReadTimeout()设置连接和读取超时时间,setDoOutput()和setDoInput()设置是否允许输出和输入,setUseCaches()设置是否使用缓存,setRequestProperty()设置请求头信息。最后通过OutputStream设置请求体。
阅读全文