have been doing Sitecheck projects, the use of the knowledge is mostly related to network programming aspects, so now there is time to use the method and some of the precautions recorded. Here I use two examples to let you know how it is used:
(1) Upload images and corresponding parameters to the server (2) upload voice and corresponding parameters to the server. Code comparison more ....
First paste the code, and then parse:
Uploadfiletask. Java: (Execution class that implements asynchronous uploads)
<span style= "FONT-SIZE:14PX;" >public class Uploadfiletask extends Asynctask<string, Void, string>{/** * variable length input parameters, with Asynctask.exucute () Correspondence */Private ProgressDialog pdialog; Private Activity Context=null; Public Uploadfiletask (Activity ctx) {this.context=ctx; Pdialog=progressdialog.show (Context, "Loading ...", "the system is processing your request"); } @Override protected void OnPostExecute (String result) {//returns the contents of the HTML page Pdialog.dismiss (); if (UploadUtils.taskSUCCESS.equals (Result)) {Toast.maketext (context, "Upload succeeded!", Toast.length_long). Show (); int size = Bimp.tempSelectBitmap.size (); while (size>0) {Imageitem Imageitem = Bimp.tempSelectBitmap.get (size-1); String Imgpath = Imageitem.getimagepath (); Remove the image from the SD card fileutils.delfile (Imgpath); Bimp.tempSelectBitmap.remove (Imageitem); bimp.max--; Get the audio data for the corresponding photo list<voice> Mdatas = StaticVariable.mapVoice.get (Imgpath); if (mdatas!=null) {int voicenum = Mdatas.size (); for (int j=0;j<voicenum;j++) {String Voicepath = Mdatas.get (j). GetFilePath (); Remove the audio Fileutils.delfile (Voicepath) from the SD card; StaticVariable.mapVoice.remove (Imgpath); }} size--; } FieldFragment.adapter.notifyDataSetChanged (); FieldFragment.imgRemark.setText (""); }else if (UploadUtils.terSUCCESS.equals (Result)) {Toast.maketext (context, "Upload succeeded!", Toast.length_long). Show (); int size = Bimp.terminalSelectBitmap.size (); while (size>0) {Imageitem Imageitem = Bimp.terminalSelectBitmap.get (size-1); if (Imageitem.iscamera ()) {//Remove Fileutil from SD cardS.delfile (Imageitem.getimagepath ()); } Bimp.terminalSelectBitmap.remove (Imageitem); bimp.terminalmax--; size--; } UpdateTerminalFragment.terminalAdapter.notifyDataSetChanged (); }else{Toast.maketext (Context, "Upload failed!", Toast.length_long). Show (); @Override protected string Doinbackground (String ... params) {string result = ""; Upload terminal picture if (Params[0].equals (staticvariable.terminal_upload_img)) {//Get the file corresponding to the photo arraylist<i mageitem> terbitmap = Bimp.terminalselectbitmap; file[] files = null; if (terbitmap!=null) {int imgnum = Terbitmap.size (); Files = new File[imgnum]; for (int i=0;i tempbitmap = Bimp.tempselectbitmap; for (int i=0;i<tempbitmap.size (); i++) {String Imgpath = Tempbitmap.get (i). Getimagepath (); Get audio data for the corresponding photo list<voice> Mdatas = StaticVariable.mapVoice.get (Imgpath); file[] voicefiles = null; if (mdatas!=null) {int voicenum = Mdatas.size (); Voicefiles = new File[voicenum]; for (int j=0;j<voicenum;j++) {String Voicepath = Mdatas.get (j). GetFilePath (); VOICEFILES[J] = new File (Voicepath); }} file File=new file (Imgpath); result = Uploadutils.uploadfile (file, Voicefiles, staticurl.urladdimg); }} return result; } @Override protected void onprogressupdate (void. .. Values) { }}</span>
This asynchronous upload processing class is relatively straightforward:
Execute the following code where you want to upload it into the asynchronous processing class:
Uploadfiletask uploadfiletask=new uploadfiletask (activity);
Uploadfiletask.execute (STATICVARIABLE.TASK_UPLOAD_IMG);
The following resolves the operation of the upload class:
result = Uploadutils.uploadfile (file, Voicefiles, staticurl.urladdimg);
File: Here is the picture files parameter
Voicefiles: This is a voice file, an array of files
Staticurl.urladdimg: File Upload Address
RESUTL: Return results
Uploadutils. Java:
<span style= "FONT-SIZE:14PX;" >public class Uploadutils {private static final int time_out = 10*10000000; Timeout time private static final String CHARSET = "Utf-8"; Set encoding public static final String failure= "0"; Upload failed return result public static final String tasksuccess= "1"; <span style= "White-space:pre" ></span>// Upload successful return result public static final String tersuccess = "2";//upload task Information public static String uploadfile (file file, file[] files, stri ng Requesturl) {String boundary = Uuid.randomuuid (). toString (); The boundary identifier is randomly generated (or can be customized) String PREFIX = "--", Line_end = "\ r \ n"; String content_type = "Multipart/form-data"; Content type (this is the standard generic type, but it is best to indicate an explicit file type) try {URL url = new URL (requesturl); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setreadtimeout (time_out); Conn.setconnecttimeout (time_out); Conn.setdoinput (true); Allow input stream Conn.setdooutput (true); Allow output stream conn.setusecaches (false); Cache Conn.setrequestmethod ("POST") is not allowed; Request Method Conn.setrequestproperty ("Charset", CHARSET); Set the encoding Conn.setrequestproperty ("Connection", "keep-alive"); Conn.setrequestproperty ("Content-type", Content_Type + " ; boundary= "+ boundary); if (file!=null) {/** * When the file is not empty, the file is packaged and uploaded */outputstream Outputsteam=conn.getoutputstream (); Obtain the output stream of the network transmission DataOutputStream dos = new DataOutputStream (outputsteam); StringBuffer sb = new StringBuffer (); Sb.append (PREFIX); Sb.append (boundary); Sb.append (Line_end); Sb.append ("Content-disposition:form-data; Name=\ "uid\" "+ line_end); The UID is the key of the upload parameter (the server side receives this parameter to correspond to this key) Sb.append (Line_end); Sb.append (Loginactivity.uid + line_end); Loginactivity.uid is the value to upload the parameter if (iscreaterecordhttp.hassamerecord==0) {sb.append (PREFIX); sb.append (boundary); Sb.append (Line_end); Sb.append ("Content-disposition:form-data; Name=\ "hassamerecord\" "+line_end); Sb.append (Line_end); Sb.append (0+line_end); Sb.append (PREFIX); Sb.append (boundary); Sb.append (line_end); Sb.append ("Content-disposition:form-data; Name=\ "isid\" "+line_end); Sb.append (Line_END); Sb.append (seetaskfragment.isid+line_end);} else if (iscreaterecordhttp.hassamerecord==1) {sb.append (PREFIX); sb.append (boundary); Sb.append (line_end); Sb.append ("Content-disposition:form-data; Name=\ "hassamerecord\" "+line_end"; Sb.append (Line_end); Sb.append (1+line_end); Sb.append (PREFIX); Sb.append (boundary); Sb.append (line_end); Sb.append ("Content-disposition:form-data; Name=\ "rid\" "+line_end"; Sb.append (Line_end); Sb.append (iscreaterecordhttp.rid+line_end);} Sb.append (PREFIX); Sb.append (boundary); Sb.append (Line_end); Sb.append ("Content-disposition:form-data; Name=\ "Remark\" "+line_end"; Sb.append (Line_end); Sb.append (Fieldfragment.getremark () + line_end);/** * Here the key NOTE: * Name inside the value for the server side need key only this key can get the corresponding file * filename is the name of the file, package For example: Abc.png */sb.append (PREFIX) with suffix name; Sb.append (boundary); Sb.append (line_end); Sb.append ("Content-disposition:form-data; Name=\ "File\"; Filename=\ "" +file.getname () + "\" "+line_end); Sb.append ("Content-type:image/jpeg"); Indicates the file type is picture JPEG type sb.append (LINE_end); Sb.append (line_end);d Os.write (Sb.tostring (). GetBytes ()); InputStream is = new FileInputStream (file); Convert picture file to binary stream into dos byte[] bytes = new Byte[1024];int len = 0;while (len=is.read (bytes))!=-1) {dos.write (bytes, 0, L EN);} Is.close ();d os.write (Line_end.getbytes ()); byte[] End_data = (prefix+boundary+prefix+line_end). GetBytes (); Dos.write (End_data);d Os.flush (); Release Stream/** * Get response Code 200 = Success * When response is successful, get response stream */int res = Conn.getresponsecode (); LOG.E ("Mine", "Response code:" +res), if (res==200) {//This is the upload success will continue to upload audio files, if you do not need to directly Returninputstrea M isre = Conn.getinputstream (); BufferedReader buffer = new BufferedReader (new InputStreamReader (Isre, "GBK")); String line = ""; StringBuffer sbre = new StringBuffer (); while (line = Buffer.readline ())! = null) {sbre.append (line);} String result = Sbre.tostring (); Gets the returned result log.e ("Mine", result); Try{jsonobject jsonobject = new Jsonobject (result); int iid = Jsonobject.getint ("IID"); String type = jsonobject.getstring ("type"); String msg = jsonobject.getstring ("msg"), if (Type.equals ("SUCCESS")) {/* in Asynctask Asynchronous processing method can no longer use asynchronous processing, cause UI (Master) thread execution error <span style= "White-space:pre" ></span>*/uploadvoice (Iid,files);}} catch (Jsonexception e) {e.printstacktrace ();} catch (ParseException E1) {e1.printstacktrace ();} return tasksuccess;}}} catch (Malformedurlexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} return FAILURE;} Upload the image corresponding to the language private static void Uploadvoice (int iid,file[] files) {String boundary = Uuid.randomuuid (). toString (); The boundary identifier randomly generates a string PREFIX = "--", Line_end = "\ r \ n"; String content_type = "Multipart/form-data"; Content type try{string Requesturl = staticurl.urladdvoices; URL url = new URL (requesturl); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setreadtimeout (time_out); Conn.setconnecttimeout (time_out); Conn.setdoinput (true); Allow input stream Conn.setdooutput (true); Allow output stream conn.setusecaches (false); Cache Conn.setrequestmethod ("POST") is not allowed; Request Method Conn.setreqUestproperty ("Charset", Charset); Set the encoding Conn.setrequestproperty ("Connection", "keep-alive"); Conn.setrequestproperty ("Content-type", Content_Type + " ; boundary= "+ boundary); if (files!=null) {/** * When the file is not empty, wrap the file and upload */outputstream outputsteam=conn.getoutputstream ();D Ataoutputstream dos = new DataOutputStream (outputsteam); StringBuffer sb = new StringBuffer (); Sb.append (PREFIX); Sb.append (boundary); Sb.append (Line_end); Sb.append ("Content-disposition:form-data; Name=\ "uid\" "+ line_end); Sb.append (line_end); Sb.append (Loginactivity.uid + line_end); Sb.append (PREFIX); Sb.append (boundary); Sb.append (line_end); Sb.append ("Content-disposition:form-data; Name=\ "iid\" "+line_end"; Sb.append (Line_end); Sb.append (iid+line_end);d Os.write (Sb.tostring (). GetBytes ()); for (file file:files) {//multiple file uploads, with Loop StringBuffer Sbimgs = new StringBuffer (); Here to note: Re-instantiate a stringbuffer, or lead to stringbuffer reuse, the original parameters are also with the subsequent parameters to the server. Set Head sbimgs.append (PREFIX); Sbimgs.append (boundary); Sbimgs.append (line_eND); Sbimgs.append ("Content-disposition:form-data; Name=\ "Voices\"; Filename=\ "" +file.getname () + "\" "+line_end) sbimgs.append (" Content-type:audio/mp3 "+line_end); SbImgs.append (line _end);//1. Write Sbdos.writebytes (sbimgs.tostring ());//Get file Fileinputstreamfileinputstream fis = new FileInputStream (file);// Set each write to 1024bytesint buffersize = 1024;byte[] buffer = new Byte[buffersize];int length = -1;//reads data from the file to the buffer while (length = f Is.read (buffer))! =-1) {dos.write (buffer, 0, length);} Dos.writebytes (Line_end), Fis.close ();d os.writebytes (line_end);d os.writebytes (line_end);} Byte[] End_data = (prefix+boundary+prefix+line_end). GetBytes ();d os.write (end_data);d Os.flush ();/** * Get response Code 200 = Success * When the response succeeds, the stream that gets the response */int res = Conn.getresponsecode (); LOG.E ("Mine", "Response code:" +res); if (res==200) {//return tersuccess;}}} catch (Malformedurlexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} return FAILURE;} Upload terminal picture public static string Uploadterfile (file[] files, string requestuRL) {String boundary = Uuid.randomuuid (). toString (); The boundary identifier randomly generates a string PREFIX = "--", Line_end = "\ r \ n"; String content_type = "Multipart/form-data"; Content type Try{url url = new URL (requesturl); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setreadtimeout (time_out); Conn.setconnecttimeout (time_out); Conn.setdoinput (true); Allow input stream Conn.setdooutput (true); Allow output stream conn.setusecaches (false); Cache Conn.setrequestmethod ("POST") is not allowed; Request Mode Conn.setrequestproperty ("Charset", Charset); Set the encoding Conn.setrequestproperty ("Connection", "keep-alive"); Conn.setrequestproperty ("Content-type", Content_Type + " ; boundary= "+ boundary); if (files!=null) {/** * When the file is not empty, wrap the file and upload */outputstream outputsteam=conn.getoutputstream ();D Ataoutputstream dos = new DataOutputStream (outputsteam); StringBuffer sb = new StringBuffer (); Sb.append (PREFIX); Sb.append (boundary); Sb.append (Line_end); Sb.append ("Content-disposition:form-data; Name=\ "uid\" "+ line_end); Sb.append (line_end); Sb.append (LoginactivIty.uid + line_end); Sb.append (PREFIX); Sb.append (boundary); Sb.append (line_end); Sb.append ("Content-disposition:form-data; Name=\ "tid\" "+line_end"; Sb.append (Line_end); Sb.append (Terminalinfo.tid+line_end); Sb.append (PREFIX); Sb.append (boundary); Sb.append (Line_end); Sb.append ("Content-disposition:form-data; Name=\ "Remark\" "+line_end"; Sb.append (Line_end); Sb.append ("Remarks" + line_end);d Os.write (Sb.tostring (). GetBytes ()); for (File file:files) {StringBuffer Sbimgs = new StringBuffer ();//Set Head sbimgs.append (PREFIX); Sbimgs.append (boundary); Sbimgs.append (line_end); Sbimgs.append ("Content-disposition:form-data; Name=\ "Imgs\"; Filename=\ "" +file.getname () + "\" "+line_end) sbimgs.append (" Content-type:image/jpeg "+line_end); SbImgs.append ( Line_end);//1. Write Sbdos.writebytes (sbimgs.tostring ());//Get file Fileinputstreamfileinputstream fis = new FileInputStream (file);// Set each write to 1024bytesint buffersize = 1024;byte[] buffer = new Byte[buffersize];int length = -1;//reads data from the file to the buffer while (length = f Is.read (buffer)! =-1) {dos.write (buffer, 0, length);} Dos.writebytes (Line_end), Fis.close ();d os.writebytes (line_end);d os.writebytes (line_end);} Byte[] End_data = (prefix+boundary+prefix+line_end). GetBytes ();d os.write (end_data);d Os.flush ();/**<span style= " White-space:pre "></span> * Get response code 200= success <span style=" White-space:pre "></span> * When the response is successful, Get the stream of the response <span style= "White-space:pre" ></span> */<span style= "White-space:pre" ></span>int Res = Conn.getresponsecode (); <span style= "White-space:pre" ></SPAN>LOG.E ("Mine", "Response code:" +res);< Span style= "White-space:pre" ></span>if (res==200) {<span style= "White-space:pre" ></span> return Tersuccess;<span style= "White-space:pre" ></span>}<span style= "White-space:pre" ></span >}<span style= "White-space:pre" ></SPAN>} catch (Malformedurlexception e) {<span style= "white-space :p Re "></span>e.printstacktrace (); <span style=" White-space:pre ">≪/span>} catch (IOException e) {<span style= "White-space:pre" ></span>e.printstacktrace (); <span Style= "White-space:pre" ></span>}<span style= "White-space:pre" ></span>return FAILURE;< Span style= "White-space:pre" ></span>}}</span>
basically mastered these methods, the operation of the upload file is the rest of the way, the binary stream to upload the file to note the file, the parameters of their head, and the tail, that is, those boundary values.
OK, that's about it, here's a recommendation for the Web-based program to upload files:
http://blog.csdn.net/carterjin/article/details/7571915
http://blog.csdn.net/lmj623565791/article/details/23781773
Android Network Programming-upload files and corresponding parameters to the server