能否再提供一个不使用Volley库的例子?
时间: 2023-03-19 18:24:30 浏览: 92
当然可以,以下是使用HttpURLConnection进行GET请求的示例代码:
```java
URL url = new URL("https://example.com/api/data"); // 请求的URL
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 创建连接对象
connection.setRequestMethod("GET"); // 设置请求方法为GET
connection.setConnectTimeout(5000); // 设置连接超时时间为5秒
connection.setReadTimeout(5000); // 设置读取超时时间为5秒
int responseCode = connection.getResponseCode(); // 获取响应码
if (responseCode == HttpURLConnection.HTTP_OK) { // 判断请求是否成功
// 读取响应数据
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder response = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
response.append(line);
}
bufferedReader.close();
inputStream.close();
String responseData = response.toString(); // 响应数据
} else {
// 请求失败,处理错误
}
```
需要注意的是,HttpURLConnection是Java标准库自带的类,因此可以不用导入任何第三方库,但是使用它需要手动处理网络请求和响应的细节,相对来说比较繁琐。