There are three steps to getting a picture on the network:
First, set permissions to connect to the network and write to read the SD card. Second, network access to obtain data flow. Third, create a folder in the SD card to stream data into a picture format storage.
Note: the Response.getentity (). GetContent () method, and this method can only be called once. otherwise it will error: Java.lang.IllegalStateException:Content has been consumed.
Manifest.xml
Assign permissions, note: Add before <application...>application>
<uses-permissionAndroid:name= "Android.permission.INTERNET"/> <uses-permissionAndroid:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permissionAndroid:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> <uses-permissionAndroid:name= "Android.permission.ACCESS_NETWORK_STATE"/>
Mainactivity.java
Get the data stream for a network picture
HttpGet Header =NewHttpGet ("Your server's picture address"); //Custom Cookies (server return)Header.setheader ("Cookie", "key")); HttpResponse Headerresponse= Httpclient.execute (header);// //headerresponse.getentity (). getcontent (); Can only be used once otherwise it will be error content has been consumedInputStream Headerin =headerresponse.getentity (). getcontent ();//data returned by the serverBitmap=Bitmapfactory.decodestream (Headerin); if(Bitmap! =NULL) {savebitmap (bitmap);//Display Image} headerin.close ();
Saved in Location:
/*** Save Method * *@throwsIOException*/ Public voidSavebitmap (Bitmap Bitmap)throwsIOException {
Change the name of String ImageName= "W" + ". jpg"; String Headpath=android.os.environment.getexternalstoragedirectory () + "/" + "MSG" + "/" + "head"; File Headdir=NewFile (Headpath); if(!headdir.exists ()) {Headdir.mkdirs (); } System.out.println (Headpath+ "\ n" +Headdir); FileOutputStream Headfos=NULL; File Headfile=NULL; Try{ //ãºã Guy Yao à Board trajectoryheadfile=NewFile (headpath,imagename); Headfile.createnewfile (); Headfos=NewFileOutputStream (Headfile); Bitmap.compress (Compressformat.jpeg,100, Headfos); Headfos.flush (); }Catch(Exception e) {e.printstacktrace (); }finally{ if(headfos!=NULL){ Try{headfos.close (); } Catch(IOException e) {e.printstacktrace (); } } } }
Android Network get pictures and save on Local