URLConnection 设置请求体
时间: 2023-10-27 21:54:51 浏览: 117
Android使用URLConnection提交请求的实现
要使用URLConnection设置请求体,你需要按照以下步骤进行操作:
1. 创建一个URL对象,指定要发送请求的目标URL。
```java
URL url = new URL("http://example.com/api/endpoint");
```
2. 打开URLConnection连接。
```java
URLConnection connection = url.openConnection();
```
3. 将URLConnection转换为HttpURLConnection(如果需要进行HTTP请求)。
```java
HttpURLConnection httpConnection = (HttpURLConnection) connection;
```
4. 设置请求方法,例如POST或PUT。
```java
httpConnection.setRequestMethod("POST");
```
5. 启用输出流和输入流。
```java
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
```
6. 设置请求头(如果需要)。
```java
httpConnection.setRequestProperty("Content-Type", "application/json");
httpConnection.setRequestProperty("Authorization", "Bearer your_token");
```
7. 获取输出流,将请求体数据写入。
```java
String requestBody = "{\"name\":\"John\",\"age\":30}";
OutputStream outputStream = httpConnection.getOutputStream();
outputStream.write(requestBody.getBytes("UTF-8"));
outputStream.close();
```
8. 发起请求并获取响应。
```java
int responseCode = httpConnection.getResponseCode();
InputStream inputStream;
if (responseCode >= 200 && responseCode < 400) {
inputStream = httpConnection.getInputStream();
} else {
inputStream = httpConnection.getErrorStream();
}
// 读取响应数据
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 处理响应数据
System.out.println(response.toString());
```
这样就可以使用URLConnection设置请求体发送HTTP请求了。请根据你的具体需求修改代码中的URL、请求方法、请求头和请求体数据。
阅读全文