法一
Button but = (Button) findViewById(R.id.button1); but.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread() { public void run() { try { writeFileData( "http://cmsimg02.qiniudn.com/contentimg/2014/06/24/20/02c9fe2c0dee6ad4a9d4761e70101452d7.jpg", "aaa.png"); } catch (Exception e) { e.printStackTrace(); } }; }.start(); } }); } public void writeFileData(String httpUrl, String fileName) { File file2 = new File(Environment.getExternalStorageDirectory() .getAbsolutePath() + "/yohoboy007/" + fileName); file2.getParentFile().mkdirs(); HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(httpUrl); InputStream inputStream = null; FileOutputStream fileOutputStream = null; try { HttpResponse httpResponse = client.execute(get); if (httpResponse.getStatusLine().getStatusCode() == 200) { inputStream = httpResponse.getEntity().getContent(); fileOutputStream = new FileOutputStream(file2); byte[] buf = new byte[1024 * 5]; int lengs; while ((lengs = inputStream.read(buf)) != -1) { fileOutputStream.write(buf, 0, lengs); } } } catch (Exception e) { e.printStackTrace(); } finally { if (inputStream != null && fileOutputStream != null) { try { inputStream.close(); fileOutputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
法二
public void method5(final String url) { // String url = // "http://cmsimg02.qiniudn.com/contentimg/2014/06/24/20/02c9fe2c0dee6ad4a9d4761e70101452d7.jpg"; YhHttpUtils.get(url, new BinaryHttpResponseHandler() { @Override public void onSuccess(byte[] arg0) { super.onSuccess(arg0); File file = Environment.getExternalStorageDirectory(); File file2 = new File(file, "yohoboy"); File file3 = new File(file2, "pic"); file3.mkdir(); file3 = new File(file3, getPicName(url)); try { FileOutputStream oStream = new FileOutputStream(file3); oStream.write(arg0); oStream.flush(); oStream.close(); // textView.setText("可爱的猫咪已经保存在sdcard里面"); } catch (Exception e) { e.printStackTrace(); Log.i("hck", e.toString()); } } }); } public String getPicName(String url) { return url.substring(url.lastIndexOf('/') + 1, url.length()); }