用HttpUrlConnection来下载文件信息
2017-11-09 15:33
288 查看
public class LoadToFile extends Activity implements View.OnClickListener { private static final String TAG = "LoadToFile"; private Button mBtn; private ImageView mImg; private String url = "http://image.tianjimedia.com/uploadImages/2014/289/01/IGS09651F94M.jpg"; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_loadfile); initView(); } private void initView() { mBtn = (Button) findViewById(R.id.btn); mBtn.setOnClickListener(this); mImg = (ImageView) findViewById(R.id.img); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn: new Thread(new Runnable() { @Override public void run() { httpRequestGet(url); } }).start(); break; default: break; } } /** * get请求 * @param loadUrl */ private void httpRequestGet(String loadUrl){ try { URL url = new URL(loadUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setRequestMethod("GET"); connection.setReadTimeout(30*1000); connection.setConnectTimeout(10*1000); connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK){ FileOutputStream fos = new FileOutputStream(new File(getFilePath())); InputStream inputStream = connection.getInputStream(); byte [] length = new byte[1024]; int l = 0; while ((l = inputStream.read(length)) != -1){ fos.write(length , 0 , l); } fos.flush(); fos.close(); }else { Log.e(TAG, "httpRequestGet--->网络请求失败"); } connection.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * 获得存储路径 * @return */ private String getFilePath(){ if (hasSDCard()){ File file = null; String filePath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/what/haha.jpeg"; file = new File(filePath); if (!file.exists()){ file.getParentFile().mkdirs(); }else { file.delete(); } return file.getPath(); }else { return null; } } /** * 判断sd卡是否存在 * @return */ private boolean hasSDCard(){ if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ return true; }else { return false; } } }
相关文章推荐
- HttpURLConnection方式下载文件之实现断点续传
- 下载网络文件HttpURLConnection.getContentLength()大小为 0
- android网络编程之HttpUrlConnection的讲解--实现文件断点下载
- android 使用AsyncHttpClient框架上传文件以及使用HttpURLConnection下载文件
- 使用HttpURLConnection下载文件
- HttpURLConnection下载文件流
- HttpURLConnection上传文件和字符串信息
- 用HttpURLConnection 下载文件工具类
- HttpURLConnection实现文件下载
- 问答邮件整理记录——HttpURLConnection下载网络文件
- 下载网络文件HttpURLConnection.getContentLength()大小为 -1
- Android - HttpURLConnection下载网络文件,加载网络图片
- Android_HttpURLConnection下载文件
- httpurlconnection不能从ftp域名下载文件吗?
- HttpURLConnection 下载文件
- java HttpURLConnection 发送文件和字符串信息
- 下载网络文件HttpURLConnection.getContentLength()大小为 -1
- 使用HttpURLConnection下载文件时出现 java.io.FileNotFoundException彻底解决办法
- android 文件下载详解(HttpURLConnection)
- Android学习之使用HttpURLConnection下载文件