For Android image transmission, Android image transmission, and XML image transmission, Android uses base64 encoding to transmit images using XML

Source: Internet
Author: User

Android client uploads images to the server and uses XML to transmit base64-encoded Images
I use the httpclient of Android to send post requests. I also want to use the post method to send data. However, the data is saved during base64 decoding on the server, I did not find the cause, so I did not write it out.

The reason why a POST request is sent is that the amount of data that can be transmitted at a time is large because the size of the image after base64 encoding is large. If you use get or other methods to transmit data, the transmission efficiency is low, the data size is limited.

1. Get the android client Image

Java code

  1. // File Operations
  2. Fileinputstream in = new fileinputstream (environment. getexternalstoragedirectory () +
    "/Images/musicmax.png ");
  3. Byte buffer [] = streamutil. Read (in); // transfers the image file to a byte array
  4. Byte [] encod = base64.encode (buffer, base64.default); // use base64 encoding
// Fileinputstream in = new fileinputstream (environment. getexternalstoragedirectory () + "/images/musicmax.png"); byte buffer [] = streamutil. read (in); // convert the image file into a byte array byte [] encod = base64.encode (buffer, base64.default); // use base64 encoding

2. Send a POST request. Pay attention to the permission to access the network on the android client.

Java code

  1. String Path = "http: // 192.168.1.173: 7999/videonews/testservlet ";
  2. Map <string, string> Params = new hashmap <string, string> (); // defines a map that stores the key-value to save the data to be transmitted.
  3. Params. Put ("value", new string (encod); // Save the data to the map object
  4. Log. I (TAG, new string (encod ));
  5. If (streamutil. sendhttpclientpostrequest (path, Params,
    "UTF-8") {// use the help class to send httpclient to send the POST request
  6. Log. I (TAG, "success:" + path +
    "----: Decode: ----" + new string (base64.decode (encod, base64.default )));
  7. }
String Path = "http: // 192.168.1.173: 7999/videonews/testservlet"; Map <string, string> Params = new hashmap <string, string> (); // define a map that saves the key-value to save the data Params to be transmitted. put ("value", new string (encod); // Save the data to the map object log. I (TAG, new string (encod); If (streamutil. sendhttpclientpostrequest (path, Params, "UTF-8") {// use the help class to send httpclient to send the POST request log. I (TAG, "success:" + path + "----: Decode: ----" + new string (base64.decode (encod, base64.default )));}

2. server code

Java code

  1. String value = request. getparameter ("value"); // obtain the value of Value
  2. Fileoutputstream fileout = new fileoutputstream ("C:/music.png"); // sets the location where the file is stored on the server.
  3. Fileout. Write (com.sun.org. Apache. xml. Internal. Security. utils. base64.decode (value. getbytes (); // use base64 for decoding
  4. Fileout. Close ();
String value = request. getparameter ("value"); // obtain the value fileoutputstream fileout = new fileoutputstream ("C:/music.png"); // set the location where the file is stored on the server fileout. write (com.sun.org. apache. XML. internal. security. utils. base64.decode (value. getbytes (); // uses base64 to decode fileout. close ();

Complete code in the streamutil help class

Java code

  1. Public class streamutil {
  2. /**
  3. * Returns a byte array.
  4. *
  5. * @ Param in the input stream
  6. * @ Return
  7. * @ Throws exception
  8. */
  9. Public static
    Byte [] Read (inputstream in) throws exception {
  10. Bytearrayoutputstream out = new bytearrayoutputstream ();
  11. If (in! = NULL ){
  12. Byte [] buffer = new
    Byte [2, 1024];
  13. Int length = 0;
  14. While (length = in. Read (buffer ))! =-1 ){
  15. Out. Write (buffer, 0, length );
  16. }
  17. Out. Close ();
  18. In. Close ();
  19. Return out. tobytearray ();
  20. }
  21. Return NULL;
  22. }
  23. /**
  24. * Use httpclient to send a POST request
  25. * @ Param path: Request Path
  26. * @ Param Params Request Parameters
  27. * @ Throws exception
  28. */
  29. Public static
    Boolean sendhttpclientpostrequest (string path, Map <string, string> Params, string encoding)
    Throws exception {
  30. List <namevaluepair> param = new arraylist <namevaluepair> ();
  31. If (Params! = NULL &&! Params. isempty ()){
  32. For (Map. Entry <string, string> entry: Params. entryset ()){
  33. Param. Add (New basicnamevaluepair (entry. getkey (), entry. getvalue ()));
  34. }
  35. }
  36. Urlencodedformentity entity = new urlencodedformentity (Param, encoding );
  37. Httppost post = new httppost (PATH );
  38. // Httpget get = new httpget ();
  39. Post. setentity (entity );
  40. Defaulthttpclient client = new defaulthttpclient ();
  41. Httpresponse response = client.exe cute (post );
  42. If (response. getstatusline (). getstatuscode () =
    (200 ){
  43. // Response. getentity (). getcontent (); // obtain the data returned by the server
  44. Return true;
  45. }
  46. Return false;
  47. }
  48. }
Public class streamutil {/*** return byte array ** @ Param in input stream * @ return * @ throws exception */public static byte [] Read (inputstream in) throws exception {bytearrayoutputstream out = new bytearrayoutputstream (); If (in! = NULL) {byte [] buffer = new byte [1024]; int length = 0; while (length = in. Read (buffer ))! =-1) {out. write (buffer, 0, length);} Out. close (); In. close (); Return out. tobytearray ();} return NULL ;} /*** use httpclient to send a POST Request * @ Param path request path * @ Param Params request parameter * @ throws exception */public static Boolean sendhttpclientpostrequest (string path, Map <string, string> Params, string encoding) throws exception {list <namevaluepair> param = new arraylist <namevaluepair> (); If (Params! = NULL &&! Params. isempty () {for (map. entry <string, string> entry: Params. entryset () {Param. add (New basicnamevaluepair (entry. getkey (), entry. getvalue () ;}} urlencodedformentity entity = new urlencodedformentity (Param, encoding); httppost post = new httppost (PATH); // httpget get = new httpget (); Post. setentity (entity); defaulthttpclient client = new defaulthttpclient (); httpresponse response = client.exe cute (post); If (response. getstatusline (). getstatuscode () = 200) {// response. getentity (). getcontent (); // get the data returned by the server return true;} return false ;}}

I have tested the POST Request Code and reported an error when the server decodes the transmitted data in base64. I did not find the specific cause, I will post the code below, and hope my friends can help me find the reason

Java code

  1. /* // File operations Note: This method has a problem in testing
  2. Fileinputstream in = new fileinputstream (environment. getexternalstoragedirectory () +
    "/Images/musicmax.png ");
  3. Byte buffer [] = streamutil. Read (in );
  4. Byte [] encod = base64.encode (buffer, base64.default );
  5. Stringbuffer sb = new stringbuffer ("value = ");
  6. URL url = new URL (PATH );
  7. Httpurlconnection conn = (httpurlconnection) URL. openconnection ();
  8. Conn. setconnecttimeout (5 *
    1000 );
  9. Conn. setrequestmethod ("Post ");
  10. Conn. setdooutput (true); // allow external data output
  11. Conn. setrequestproperty ("Content-Type ",
    "Application/X-WWW-form-urlencoded ");
  12. Conn. setrequestproperty ("Content-Length", (sb. tostring (). getbytes (). Length + encod. Length) +
    "");
  13. Outputstream outs = conn. getoutputstream ();
  14. Outs. Write (sb. tostring (). getbytes ());
  15. Outs. Write (encod );
  16. Outs. Close ();
  17. Log. I (TAG, new string (encod ));
  18. If (conn. getresponsecode () =
    (200 ){
  19. Log. I (TAG, "success:" + path +
    "----: Decode: ----" + new string (base64.decode (encod, base64.default )));
  20. // The following code is used to test whether the corresponding image can be generated after decoding.
  21. // Fileoutputstream fileout = new fileoutputstream (environment. getexternalstoragedirectory () + "/images/musicmax1.png ");
  22. // Fileout. Write (base64.decode (encod, base64.default ));
  23. // Fileout. Close ();
  24. }
/* // File operations Note: This method has a problem in testing fileinputstream in = new fileinputstream (environment. getexternalstoragedirectory () + "/images/musicmax.png"); byte buffer [] = streamutil. read (in); byte [] encod = base64.encode (buffer, base64.default); stringbuffer sb = new stringbuffer ("value ="); Url url = new URL (PATH ); httpurlconnection conn = (httpurlconnection) URL. openconnection (); Conn. setconnecttimeout (5*1000); Conn. setrequestmethod ("Post"); Conn. setdooutput (true); // allow external output of data Conn. setrequestproperty ("Content-Type", "application/X-WWW-form-urlencoded"); Conn. setrequestproperty ("Content-Length", (sb. tostring (). getbytes (). length + encod. length) + ""); outputstream outs = Conn. getoutputstream (); outs. write (sb. tostring (). getbytes (); outs. write (encod); outs. close (); log. I (TAG, new string (encod); If (Conn. getresponsecode () = 200) {log. I (TAG, "success:" + path + "----: Decode: ----" + new string (base64.decode (encod, base64.default ))); // The following code is used to test whether the corresponding image can be generated after decoding. // fileoutputstream fileout = new fileoutputstream (environment. getexternalstoragedirectory () + "/images/musicmax1.png"); // fileout. write (base64.decode (encod, base64.default); // fileout. close ();}

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.