Android studio 使用httpurlconnection 网络访问中怎样创建 HttpURLConnection 对象
时间: 2024-06-09 10:06:49 浏览: 166
Android使用HttpURLConnection访问网络
在 Android Studio 中使用 HttpURLConnection 进行网络访问,需要进行如下步骤创建 HttpURLConnection 对象:
1. 创建 URL 对象,指定要访问的 URL。
```java
URL url = new URL("http://www.example.com");
```
2. 打开连接,并获取 HttpURLConnection 对象。
```java
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
```
3. 设置请求方法(GET、POST等)。
```java
conn.setRequestMethod("GET");
```
4. 设置连接超时时间和读取超时时间。
```java
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
```
5. 设置是否允许输入输出。
```java
conn.setDoInput(true);
conn.setDoOutput(true);
```
6. 添加请求头信息。
```java
conn.setRequestProperty("Content-Type", "application/json");
```
7. 获取服务器返回的响应码。
```java
int responseCode = conn.getResponseCode();
```
8. 获取服务器返回的输入流,读取响应数据。
```java
InputStream inputStream = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
```
9. 关闭 HttpURLConnection 连接。
```java
conn.disconnect();
```
完整代码示例:
```java
try {
URL url = new URL("http://www.example.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
int responseCode = conn.getResponseCode();
InputStream inputStream = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
conn.disconnect();
// 处理响应数据
String responseData = response.toString();
// ...
} catch (Exception e) {
e.printStackTrace();
}
```
阅读全文