java调用http接口的put请求,给出完整的代码示例和注释
时间: 2023-06-01 08:05:26 浏览: 640
以下是Java调用http接口的PUT请求的完整代码示例和注释:
```
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpPutExample {
public static void main(String[] args) throws IOException {
// 创建URL对象,指向要请求的API接口地址
URL url = new URL("http://example.com/api/user/123");
// 创建HttpURLConnection对象,用于发送PUT请求
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("PUT"); // 设置请求方法为PUT
// 设置请求头信息
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Authorization", "Bearer abcdefg123456");
// 设置请求体内容
String requestBody = "{\"name\":\"John Doe\",\"email\":\"john.doe@example.com\"}";
con.setDoOutput(true);
con.getOutputStream().write(requestBody.getBytes());
// 发送PUT请求,并获取响应码
int responseCode = con.getResponseCode();
// 打印响应码
System.out.println("Response code: " + responseCode);
// 如果响应码为200或204,则表示请求成功,可以获取响应体内容
if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
String responseBody = new String(con.getInputStream().readAllBytes());
System.out.println("Response body: " + responseBody);
}
// 关闭连接
con.disconnect();
}
}
```
注释:
1. 创建URL对象,指向要请求的API接口地址。
2. 创建HttpURLConnection对象,用于发送PUT请求。
3. 设置请求方法为PUT。
4. 设置请求头信息,比如Content-Type指定请求体格式为JSON,Accept指定响应体格式为JSON,Authorization指定访问令牌。
5. 设置请求体内容,比如要更新用户信息为John Doe和john.doe@example.com。
6. 发送PUT请求,并获取响应码。
7. 打印响应码。
8. 如果响应码为200或204,则表示请求成功,可以获取响应体内容。
9. 关闭连接。
请注意,此示例仅供参考。实际情况下,您需要根据具体的接口文档和参数要求来编写代码。同时也需要处理异常和错误情况,保证代码的稳定性和可靠性。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.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)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)