通过http协议获取后台数据

这段代码展示了如何使用HTTP GET请求从后台获取数据,并将其保存到本地文件中。通过`getInputStream()`方法建立URL连接,设置超时时间,然后读取响应数据,最后将数据写入文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public void saveToDis() {
InputStream inputStream = getInputStream();
byte[] data = new byte[1024];
int len = 0;
FileOutputStream outputStream = null;
try {
// 读取后台数据存储位置
String fileName = "";
outputStream = new FileOutputStream(fileName);
while ((len = inputStream.read(data)) != -1) {
outputStream.write(data, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != inputStream) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != outputStream) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}


}
//数据输入流
public InputStream getInputStream() {
InputStream inputStream = null;
HttpURLConnection httpConnection = null;
try {
URL url = new URL(path);
if (url != null) {
httpConnection = (HttpURLConnection) url.openConnection();
// 设置连接网络时间超时
httpConnection.setConnectTimeout(3000);
//设置为true表示能够用URL连接进行输入
httpConnection.setDoInput(true);
httpConnection.setRequestMethod("GET");


int requestCode = httpConnection.getResponseCode();


if (200 == requestCode) {
// 从服务器端获取输入流
inputStream = httpConnection.getInputStream();
}
}


} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}


return inputStream;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值