《string》
<string name="error">error</string>
<string name="default_url">"http://172.17.21.231:8080/web/gg.jpg"</string>
《manife》
<uses-permission android:name="android.permission.INTERNET"/>
《StreamTool.java》
package cn.itcast.utils; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; public class StreamTool { /** * 读取流中的数据 * @param inStream * @return */ public static byte[] read(InputStream inStream) { // TODO Auto-generated method stub ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; try { while ( -1!=(len=inStream.read(buffer)) ) { outStream.write(buffer, 0, len); } inStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return outStream.toByteArray(); } }
《》
package cn.itcast.service; import java.io.InputStream; import java.net.URL; import javax.net.ssl.HttpsURLConnection; import cn.itcast.utils.StreamTool; public class ImageService { /** * 获取网络图片数据 * @param path 网络图片URL * @return */ public static byte[] getImage(String path) throws Exception{ // TODO Auto-generated method stub URL url = new URL(path); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); if (conn.getResponseCode()==200){ InputStream inStream = conn.getInputStream(); byte[] res = StreamTool.read(inStream); } return null; } }
<MainActivity.java>
private class ButtonClickListenner implements View.OnClickListener{ public void onClick(View v) { String path = pathText.getText().toString(); try { byte[] data = ImageService.getImage(path); Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); imageView.setImageBitmap(bitmap); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); Toast.makeText(getApplicationContext(), R.string.error, 1).show(); } }