Java的HttpUtils类, 下载图片用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
package com.example.lcheng215.fixture; import android.util.Log; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; /** * Created by Lcheng 215 on 2015-9-24. */ public class HttpUtils { //private final static String URL_PATH = "http://192.168.6.9/webel/images/corporate.png"; private final static String URL_PATH = "http://c.hiphotos.baidu.com/album/w%3D2048/sign=aa13cdbb023b5bb5bed727fe02ebd539/7dd98d1001e93901a318412e7aec54e736d1968c.jpg"; public static InputStream getImageViewInputStream() throws IOException{ InputStream inputStream = null; URL url = new URL(URL_PATH); if(url != null){ HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection(); httpURLConnection.setConnectTimeout(3000); httpURLConnection.setRequestMethod("GET"); httpURLConnection.setDoInput(true); int response_code = httpURLConnection.getResponseCode(); if(response_code == 200){ inputStream = httpURLConnection.getInputStream(); } } return inputStream; } public static byte[] getImageViewArray(){ byte[] data = null; InputStream inputStream = null; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try{ Log.v("kkk", "in class HttpUtils getImageViewArray()"); Log.v("kkk", URL_PATH); URL url = new URL(URL_PATH); if(url != null){ Log.v("kkk", "url not null"); HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection(); Log.v("kkk", "httpURLConnection implented"); httpURLConnection.setConnectTimeout(3000); Log.v("kkk", "after setConnecttimeout()"); httpURLConnection.setRequestMethod("GET"); Log.v("kkk", "after setRequestMethod()"); httpURLConnection.setDoInput(true); Log.v("kkk", "after setDoInput()"); int response_code = httpURLConnection.getResponseCode(); //int response_code = 200; Log.v("kkk", "after getResponseCode():"); if(response_code == 200){ int len = 0; byte[] b_data = new byte[1024]; Log.v("kkk","connection 200, ok"); inputStream = httpURLConnection.getInputStream(); while ((len = inputStream.read(b_data)) != -1){ outputStream.write(b_data,0,len); } data = outputStream.toByteArray(); } } }catch (Exception e){ e.printStackTrace(); }finally { if(inputStream != null){ try{ inputStream.close(); }catch (IOException e){ e.printStackTrace(); } } } return data; } } |