android HttpURLConnection 实现下载

本文提供了一个使用Java进行网络数据下载的示例代码。通过创建URL对象并建立HttpURLConnection连接,可以读取指定URL的内容,并将其逐行读取到StringBuilder中。文中详细展示了如何处理可能出现的异常。

public String download(String urlStr) {

StringBuilder sb = new StringBuilder()

try {
// 创建一个URL对象
url = new URL("http://www.baidu.com");
// 创建一个Http连接
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
BufferedReader buffer = new BufferedReader(new InputStreamReader(
urlConn.getInputStream()));
System.out.println("buffer");
// 逐行读数据
String line = null;
while ((line = buffer.readLine()) != null) {
System.out.println("line" + line);
sb.append(line);
}
Log.e("RS", sb.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {

buffer.close();
 urlConn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
return sb.toString();
}
Android中使用HttpURLConnection实现GET请求并传参,可将参数附加到URL后面,以下是示例代码: ```java try { // 定义请求的基础URL String baseUrl = "http://www.example.com/data"; // 定义要传递的参数 String param1 = "value1"; String param2 = "value2"; // 构建完整的URL,将参数附加到基础URL后面 String fullUrl = baseUrl + "?param1=" + param1 + "&param2=" + param2; // 创建URL对象 URL url = new URL(fullUrl); // 打开连接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置请求方法为GET connection.setRequestMethod("GET"); // 设置连接超时时间 connection.setConnectTimeout(6000); // 设置读取超时时间 connection.setReadTimeout(6000); // 获取响应码 int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // 请求成功,获取服务器响应的数据 InputStream inputStream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } // 处理服务器响应的数据 String responseData = response.toString(); // 在这里进行数据处理 } else { // 请求失败,处理错误情况 } // 断开连接 connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } ``` 上述代码首先构建了一个包含参数的完整URL,然后使用HttpURLConnection打开连接,设置请求方法为GET,设置超时时间,获取响应码,根据响应码判断请求是否成功,最后处理响应数据并断开连接。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值