Android uses post to upload pictures to the server method _android

Source: Internet
Author: User
Tags response code uuid stringbuffer

This article describes how Android uses post to upload pictures to the server. Share to everyone for your reference, specific as follows:

/** * Upload files to server class * * @author Tom/public class Uploadutil {private static final String TAG = "UploadFile"; private static final int time_out = 10 * 1000; Timeout time private static final String CHARSET = "Utf-8"; 
  Set Code/** * Android upload file to server * * @param file needs to upload files * @param requesturl requested Rul * @return return the response content * *
    public static string UploadFile (file file, string requesturl) {string result = NULL; String boundary = Uuid.randomuuid (). toString ();
    Boundary identification randomly generated 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); Caching Conn.setrequestmethod ("POST") is not allowed; Request Mode Conn.setrequestproperty ("ChArset ", CHARSET);
      Set encoding Conn.setrequestproperty ("Connection", "keep-alive");
      Conn.setrequestproperty ("Content-type", Content_Type + "; boundary=" + boundary); if (file!= null) {/** * When files are not empty, wrap the file and upload/DataOutputStream dos = new Dataoutputstrea
        M (Conn.getoutputstream ());
        StringBuffer sb = new StringBuffer ();
        Sb.append (PREFIX);
        Sb.append (boundary);
        Sb.append (Line_end);
        /** * Here is the key note: The value of the name inside the server needs key only this key can get the corresponding file * filename is the name of the file, including the suffix name, such as: abc.png * * Sb.append ("Content-disposition:form-data; Name=\ "Uploadfile\";
        Filename=\ "" + file.getname () + "\" + line_end); Sb.append ("Content-type:application/octet-stream;
        Charset= "+ charset + line_end);
        Sb.append (Line_end);
        Dos.write (Sb.tostring (). GetBytes ());
        InputStream is = new FileInputStream (file);
        byte[] bytes = new byte[1024];
      int len = 0;  while (len = is.read (bytes))!=-1) {dos.write (bytes, 0, Len);
        } is.close ();
        Dos.write (Line_end.getbytes ());
        Byte[] End_data = (PREFIX + boundary + PREFIX + line_end). GetBytes ();
        Dos.write (End_data);
        Dos.flush ();
        /** * Get response code 200 = Success When the response succeeds, get the response stream */int res = Conn.getresponsecode ();
        LOG.E (TAG, "Response code:" + res);
        if (res==200)//{LOG.E (TAG, "request Success");
        InputStream input = Conn.getinputstream ();
        StringBuffer sb1 = new StringBuffer ();
        int SS;
        while (ss = Input.read ())!=-1) {sb1.append ((char) SS);
        result = Sb1.tostring ();
        LOG.E (TAG, "Result:" + result);
        ///else{//LOG.E (TAG, "request Error");
    A catch (Malformedurlexception e) {e.printstacktrace ());
    catch (IOException e) {e.printstacktrace (); } rEturn result; /** * Constructs the request content through splicing, implements the parameter transmission and the file transfer * * @param URL Service net address * @param params text content * @pa Ram Files Pictures * @return String result of Service response * @throws ioexception/public static String PO St (string URL, map<string, string> params, map<string, file> files) throws IOException {string Boun
    Dary = 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 (URL);
    HttpURLConnection conn = (httpurlconnection) uri.openconnection (); Conn.setreadtimeout (10 * 1000); Maximum cache time Conn.setdoinput (true);//Allow input conn.setdooutput (true);//Allow output conn.setusecaches (false);
    Caching 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 the parameters of the group spelling text 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 StringBuilder ();
        Sb1.append (PREFIX);
        Sb1.append (boundary);
        Sb1.append (Linend); Sb1.append ("Content-disposition:form-data; Name=\ "Uploadfile\";
        Filename=\ "" + file.getvalue (). GetName () + "\" "+ 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 ();
    StringBuilder SB2 = new StringBuilder ();
      if (res = =) {int ch;
      while (ch = in.read ())!=-1) {sb2.append ((char) ch);
    } outstream.close (); Conn.disconnect ();
    return sb2.tostring ();

 }
}

The example invokes the second way of uploading:

Final map<string, string> params = new hashmap<string, string> ();
Params.put ("Send_userid", string.valueof (ID));
Params.put ("Send_email", address);
Params.put ("Send_name", name);
Params.put ("Receive_email", emails);
Final map<string, file> files = new hashmap<string, file> ();
Files.put ("UploadFile", file);
Final String request = Uploadutil.post (Requesturl, params, files);

For more information on Android-related content readers can view the site topics: "Android Debugging techniques and common problems solution summary", "Android Development introduction and Advanced Course", "Android Multimedia operating skills Summary (audio, video, recording, etc.)", " Android Basic Components Usage Summary, Android View tips Summary, Android layout layout tips and Android Control usage summary

I hope this article will help you with the Android program.

Related Article

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.