public void Download(final String path){
//将用户信息传入服务器
new Thread(){
@Override
public void run() {
super.run();
try {
URL url = new URL(path);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(5000);//推荐设置网络延时
httpURLConnection.setReadTimeout(5000);//设置从主机读取数据超时(单位:毫秒)
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoInput(true);
httpURLConnection.connect(); //此处必须显式进行连接
//以下同Post
//获取响应的状态码,判断是否请求成功
if(httpURLConnection.getResponseCode()==HttpURLConnection.HTTP_OK){
//获得网络字节输入流对象
InputStream is=httpURLConnection.getInputStream();// 不是操作文件的吗
//建立内存到硬盘的连接
System.out.println("111");
FileOutputStream fos=new FileOutputStream(new File(Environment.getExternalStorageDirectory() + "/Pictures/ss.jpg"));
System.out.println("222");
//老三样 写文件
byte[] b=new byte[4 * 1024];
int len=0;
while((len=is.read(b))!=-1){ //先读到内存
fos.write(b, 0, len);
}
System.out.println("下载成功");
fos.flush();
fos.close();
}
}catch (IOException ioe){
}
}
}.start();
}
记得Android6.0需要动态申请读写sd卡权限。权限申请可参考https://blog.csdn.net/qq_38367681/article/details/103794429