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
- // File Operations
- Fileinputstream in = new fileinputstream (environment. getexternalstoragedirectory () +
"/Images/musicmax.png ");
- Byte buffer [] = streamutil. Read (in); // transfers the image file to a byte array
- 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
- String Path = "http: // 192.168.1.173: 7999/videonews/testservlet ";
- Map <string, string> Params = new hashmap <string, string> (); // defines a map that stores the key-value to save the data to be transmitted.
- Params. 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 )));
- }
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
- String value = request. getparameter ("value"); // obtain the value of Value
- Fileoutputstream fileout = new fileoutputstream ("C:/music.png"); // sets the location where the file is stored on the server.
- Fileout. Write (com.sun.org. Apache. xml. Internal. Security. utils. base64.decode (value. getbytes (); // use base64 for decoding
- 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
- Public class streamutil {
- /**
- * Returns a byte array.
- *
- * @ Param in the input stream
- * @ Return
- * @ Throws exception
- */
- Public static
Byte [] Read (inputstream in) throws exception {
- Bytearrayoutputstream out = new bytearrayoutputstream ();
- If (in! = NULL ){
- Byte [] buffer = new
Byte [2, 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 Parameters
- * @ 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 (); // obtain the data returned by the server
- Return true;
- }
- Return false;
- }
- }
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
- /* // 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 data output
- 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 ();
- }
/* // 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 ();}