Android client passes pictures to server (using HTTP protocol)

Source: Internet
Author: User

To pass a picture to the server using the HTTP protocol, first understand the message format inside the HTTP protocol message:

Web-side pass-through pictures are usually delivered as forms, delivered via post, where two jar packages are used, namely Commons-fileupload.jar and Commons-io.jar jar packages.

The following is the format of the HTTP protocol upload file header file:

In fact, our front and back interaction is the HTTP protocol used. The HTTP protocol, by default, is a string that is passed. So we upload the file words to add enctype = "Multipart/form-data" This parameter to show that we pass the file is not a string. When we do Web development, the browser automatically resolves the HTTP protocol. We don't have to take care of what's in there. Just remember a couple of parameters on the line. The file message we are uploading is stored in the requested header file. Here is the format for uploading the file header file:

POST/logsys/home/uploadispeedlog!dodefault.html http/1.1

Accept:text/plain, */*  

accept-language:zh-cn 

host:192.168.24.56

content-type:multipart/form-data;boundary=-----------------------------7db372eb000e2

user-agent:winhttpclient

content-length:3693

connection:keep-alive

-------------------------------7db372eb000e2

  Content-disposition:form-data; Name= "File"; Filename= "Kn.jpg"

Content-type:image/jpeg

(Omit JPEG file binary data here ...) )

  -------------------------------7db372eb000e2--

This is the file format that HTTP uploads send. And we want to send the time must follow this format and can not make a bit of error, including the return of each line, the following paragraph of text is on the internet to find the feeling to write more wonderful. (Respect for original: http://topmanopensource.iteye.com/blog/1605238)

The Red Font section is the head of the protocol. When uploading data to the server, not every field of the protocol header is stated, where Content-type is required, and includes a flag of a similar flag character named boundary, which can be a random input string. It is also necessary to follow the specific content. It is used to tell the beginning of a piece of content. content-length:3693, 3693 Here is the total length of the file to be uploaded. The green font part is the data that needs to be uploaded, can be text, it can be pictures and so on. Content-disposition, Content-type, and content-transfer-encoding are required in front of the data content. The final purple part is the end of the protocol.
Note This line:
Content-type:multipart/form-data; boundary=---------------------------7db372eb000e2
According to rfc1867, Multipart/form-data is a must.
---------------------------7db372eb000e2 is a delimiter that separates multiple files and form items. Where B372eb000e2 is a number that is generated on the fly to ensure that the entire delimiter does not appear in the contents of a file or form item. Each part of the form is separated by a delimiter, and the delimiter must be preceded by a "--" two characters (that is,--{boundary}) to be considered as the delimiter of the form by the HTTP protocol, and the end by adding "--" after the correct delimiter to indicate the end.
The front---------------------------7d is the unique symbol of IE, Mozila for---------------------------71.

Simply comb the header of these HTTP protocols and then pass the image to the server: directly on the code:

Client code
public class HttpPost {/** * Constructs the request content through stitching, implements the parameter transfer and the file transfer * * @param acti *. nurl * @param params * @param files * @return * @throws ioexception */public static string post (string ActionURL, map<string, string> params, map<st Ring, file> files) throws IOException {String boundary = Java.util.UUID.randomUUID (). toString (); String PREFIX = "--", Linend = "\ r \ n"; String multipart_from_data = "Multipart/form-data"; String CHARSET = "UTF-8"; URL uri = new URL (actionurl); HttpURLConnection conn = (httpurlconnection) uri.openconnection (); Conn.setreadtimeout (5 * 1000); The maximum time to cache Conn.setdoinput (TRUE);//Allow input conn.setdooutput (true);//Allow output conn.setusecaches (false); Cache Conn.setrequestmethod ("POST") is not allowed, conn.setrequestproperty ("Connection", "keep-alive"); Conn.setrequestproperty ("Charsert", "UTF-8"); Conn.setrequestproperty ("Content-type", Multipart_from_data + "; boundary= "+ boundary);//First set the parameters of the spelling type StringBuilder SB = new StringBuilder (); for (map.entry<string, string> Entry:Params.entryset ()) {sb.append (PREFIX); sb.append (boundary); Sb.append (linend); Sb.append ("Content-disposition: Form-data; Name=\ "" + entry.getkey () + "\" "+ linend); Sb.append (" Content-type:text/plain; Charset= "+ charset + linend); Sb.append (" content-transfer-encoding:8bit "+ linend); Sb.append (linend); Sb.append ( Entry.getvalue ()); Sb.append (linend);} DataOutputStream OutStream = new DataOutputStream (Conn.getoutputstream ()); Outstream.write (Sb.toString (). GetBytes () );//Send file data if (Files! = null) for (map.entry<string, file> file:files.entrySet ()) {StringBuilder SB1 = new Stringbu Ilder (); Sb1.append (PREFIX); sb1.append (boundary); Sb1.append (linend); Sb1.append ("Content-disposition:form-data"; Name=\ "File\"; Filename=\ "" + file.getkey () + "\" "+ linend); Sb1.append (" Content-type:application/octet-stream; Charset= "+ charset + linend); Sb1.append (linend); Outstream.write (Sb1.tostring (). GetBytes ()); InputStream is = new FileInputStream (File.getvalue ()); byte[] buffer = new Byte[1024];int len = 0;whiLe (len = is.read (buffer))! =-1) {outstream.write (buffer, 0, Len);} Is.close (); Outstream.write (Linend.getbytes ());} Request End Flag byte[] End_data = (PREFIX + boundary + PREFIX + linend). GetBytes (); Outstream.write (End_data); Outstream.flush () ;//Get Response code int res = Conn.getresponsecode (); InputStream in = Conn.getinputstream (); if (res = =) {int ch; StringBuilder SB2 = new StringBuilder (), while ((ch = in.read ())! =-1) {sb2.append ((char) ch);}} Outstream.close (); Conn.disconnect (); return in.tostring ();}}

Below is the server code:

public class Uploadservlet extends HttpServlet {private static final long Serialversionuid = 1l;/** * Default constructor. */public Uploadservlet () {//TODO auto-generated Constructor stub}/** * @see Httpservlet#doget (httpservletrequest reques T, HttpServletResponse * response) */protected void doget (httpservletrequest request,httpservletresponse response) th Rows Servletexception, IOException {//TODO auto-generated method stub}/** * @see Httpservlet#dopost (HttpServletRequest R Equest, HttpServletResponse * response) */public void DoPost (HttpServletRequest request, httpservletresponse response ) throws Servletexception, IOException {requestcontext req = new Servletrequestcontext (request); Fileupload.ismultipartcontent (req)) {Diskfileitemfactory factory = new Diskfileitemfactory (); Servletfileupload fileUpload = new Servletfileupload (factory); Fileupload.setfilesizemax (1024 * 1024 * 1024); List items = new ArrayList (); try {items = fileupload.parserequest (request);} catch (Exception e) {}iterator it = Items.iterator (); while (It.hasnext ()) {Fileitem Fileitem = (fileitem) it.next (); if (Fileitem.isformfi Eld ()) {System.out.println (Fileitem.getfieldname () + "" + fileitem.getname () + "" + New String (Fileitem.getstring (). GetBytes ("Iso-8859-1"), "GBK");} else {System.out.println (Fileitem.getfieldname () + "" + fileitem.getname () + "" + fileitem.isinmemory () + "" + FILEITEM.G Etcontenttype () + "" + fileitem.getsize ()); if (Fileitem.getname ()! = null && fileitem.getsize ()! = 0) {File Fullfi Le = new File (Fileitem.getname ()); File NewFile = new file ("f:\\upload\\" + fullfile.getname ()); try {fileitem.write (newFile);} catch (Exception E) {}} else {S Ystem.out.println ("No file choosen or empty file");}}}}

Android client passes pictures to server (using HTTP protocol)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.