java调用http接口的put请求,给出完整的代码示例和注释
时间: 2023-06-01 09:05:52 浏览: 362
好的,下面是 Java 调用 HTTP 接口的 PUT 请求的代码示例和注释,希望能帮到您:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
public class HttpUtil {
/**
* 发送 PUT 请求
*
* @param url 请求的 URL 地址
* @param params 请求的参数,格式为 Map<String, String>
* @return String
* @throws Exception
*/
public static String sendPut(String url, Map<String, String> params) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法为 PUT
con.setRequestMethod("PUT");
// 设置请求头部分参数
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// 发送 PUT 请求
con.setDoOutput(true);
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, String> param : params.entrySet()) {
if (postData.length() != 0) {
postData.append('&');
}
postData.append(param.getKey());
postData.append('=');
postData.append(param.getValue());
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
con.getOutputStream().write(postDataBytes);
// 获取响应结果
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
}
```
注意事项:
1. 该代码是通过 HttpURLConnection 实现的 PUT 请求,可以根据需求选择其他方式实现。
2. 参数 params 是请求的参数,以 Map<String, String> 的形式传入。
3. 代码实现了设置请求头的功能,可以根据需求添加或修改请求头的参数。
4. 在发送 PUT 请求时,需要将请求参数写入到请求体中。
5. 代码中获取响应结果的方式是通过 BufferedReader 读取响应结果,可以根据需求使用其他方法获取响应结果。
6. 该代码仅供参考,由于每个项目的具体需求不同,可能需要根据实际情况进行修改和完善。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)