URLConnection和HttpURLConnection都是用于建立(应用层的)网络连接的类。
URLConnection是一种通用的连接方式,它支持多种协议,如 HTTP、HTTPS、FTP 等。
HttpURLConnection是URLConnection的子类,提供了更多针对HTTP协议的功能。
如果仅是简单的HttpURLConnection的get服务,使用URLConnection即可。(如获取网络图片)
OKHttpClient是第三方提供,对HttpURLConnection的升级;相对于HttpURLConnection更建议使用OKHttpClient。
//目标地址
String imagePath="XXXX.jpg";
//私有文件-文件名
String fileName="fileName.XXX";
//创建URL
URL url=new URL(path);
//打开通道(连接)
URLConnection urlConnection=url.openConnection();
//获取数据输入流
InputStream inputStream=urlConnection.getInputStream();
//创建输出流
FileOutputStream fileOutputStream=openFileOutput(fileName,MODE_PRIVATE);
//存储数据
//缓存区-用于存储数据
byte bytes[]=new byte[4096];
//存储数据
while (true){
if(inputStream.read(bytes,0,bytes.length)!=-1){
fileOutputStream.write(bytes,0,bytes.length);
} else {
break;
}
}
//关闭流
fileOutputStream.close();
inputStream.close();
//关闭通道(连接)
urlConnection.disconnect();
tag:http;URLConnection;urlconnection;HttpURLConnection;httpurlonnection;OKHttpClient;okhttpclient;网络;网络连接