(Android)HttpURLCOnnection用法
时间: 2023-08-24 18:07:14 浏览: 93
HttpURLConnection是Android中用于发送HTTP网络请求的类,可以用来发送GET、POST等请求,也可以设置请求头、请求体等信息。
以下是HttpURLConnection的使用步骤:
1. 创建URL对象
```java
URL url = new URL("http://www.example.com");
```
2. 打开URL连接
```java
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
```
3. 设置请求方法
```java
conn.setRequestMethod("GET"); // 或者 "POST"
```
4. 设置请求头
```java
conn.setRequestProperty("Content-Type", "application/json"); // 设置请求体类型为JSON
```
5. 设置请求体(可选)
```java
String requestBody = "{\"name\": \"John\", \"age\": 30}";
OutputStream outputStream = conn.getOutputStream();
outputStream.write(requestBody.getBytes());
```
6. 获取响应码
```java
int responseCode = conn.getResponseCode();
```
7. 获取响应体
```java
InputStream inputStream = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
String responseBody = response.toString();
```
8. 断开连接
```java
conn.disconnect();
```
需要注意的是,HttpURLConnection默认使用缓存,如果需要禁用缓存可以添加以下代码:
```java
conn.setUseCaches(false);
```
阅读全文