HttpURLConnection 获取返回结果
时间: 2023-10-12 13:07:14 浏览: 52
使用HttpURLConnection获取返回结果可以通过以下步骤实现:
1. 创建一个HttpURLConnection对象并设置请求方法、请求头等参数。
```
URL url = new URL("http://www.example.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "application/json");
```
2. 发送请求并获取响应状态码。
```
int responseCode = conn.getResponseCode();
```
3. 判断响应状态码是否为200,如果是则读取响应数据。
```
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String responseBody = response.toString();
}
```
4. 关闭连接。
```
conn.disconnect();
```
注意,以上代码仅供参考,具体实现可能会有所不同。另外,获取返回结果的过程应该放在子线程中进行,以免阻塞主线程。