用java封装一个put请求的方法
时间: 2024-03-06 20:47:05 浏览: 14
下面是用Java封装一个PUT请求的方法的代码示例:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpPutRequest {
public static void main(String[] args) {
String url = "http://example.com/api/endpoint";
String jsonRequestBody = "{\"name\":\"John\", \"age\":30}";
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置PUT请求
con.setRequestMethod("PUT");
// 设置请求头
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Content-Type", "application/json");
// 发送请求
con.setDoOutput(true);
byte[] requestBodyBytes = jsonRequestBody.getBytes("utf-8");
con.getOutputStream().write(requestBodyBytes);
// 处理响应
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Response Code : " + responseCode);
System.out.println("Response Body : " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在这个示例中,我们使用HttpURLConnection来发送PUT请求。我们首先设置请求方法为PUT,然后设置请求头中的Content-Type,以指定请求体的类型为JSON。接着,我们将请求体转换为字节数组,并将其写入请求的输出流中。最后,我们处理响应并输出响应代码和响应主体。