Interface Documentation:
Change Avatar interface User/change_avatar send data http Post body (altogether 2 to Key-value): json={"UID": "1", "Sid": " 0123456789abcdef0123456789abcdef "," ver ":" 1 "," request ": {}}file= picture binary file data return data {" ret ": 0," response ": { " status " : 1, "url": "http://192.168.1.200:8088/thumb.php?src=984340199_1667541218_1540991412.jpg&t=a&w=112 &h=112 " }}
Problems encountered:
First, when the binary request body parameters are encapsulated, the delivery parameters are insufficient, causing the server side to not recognize the POST request.
Httputils http =Newhttputils (); Requestparams params=NewRequestparams (); Params.addbodyparameter ("JSON", JSON); for(inti = 0; I < files.size (); i++) { if(Files.get (i)! =NULL) { Try{params.addbodyparameter ("File" +i,NewFileInputStream (Files.get (i)), Files.get (i). Length (), Files.get (i) . GetName (),"Application/octet-stream"); } Catch(FileNotFoundException e) {e.printstacktrace (); } } }
Params.addbodyparameter (key, stream, length, fileName, MimeType);
Then, when the POST request is sent, an async method is used, resulting in the inability to return the value returned by the server.
NULL ; Try { // synchronous method, gets the server-side returned stream responsestream responsestream = Http.sendsync ( Httpmethod.post, URL, params); = responsestream.readstring (); Catch (Exception e) { e.printstacktrace (); } return s;
Responsestream Responsestream = Http.sendsync (method, URL, params);
The complete code to send the POST request is attached below:
/*** Send a POST request, carry JSON and multiple file parameters to get the result returned by the server (JSON format) *@paramURL Request Address *@paramJSON string encapsulated in the JSON request body *@paramlist<file> Uploading multiple files *@returnresults returned by the String server*/ Public StaticString sendpost (string URL, string json, list<file>files) {httputils http=Newhttputils (); Requestparams params=NewRequestparams (); Params.addbodyparameter ("JSON", JSON); if(files.size () = = 1) { Try{params.addbodyparameter ("File", NewFileInputStream (files.get (0)), Files.get (0). Length (), Files.get (0). GetName (),"Application/octet-stream"); } Catch(FileNotFoundException e) {e.printstacktrace (); } } Else { for(inti = 0; I < files.size (); i++) { if(Files.get (i)! =NULL) { Try{params.addbodyparameter ("File" +I,NewFileInputStream (Files.get (i)), Files.get (i). Length (), Files.get (i). GetName (), "Application/octet-stream"); } Catch(FileNotFoundException e) {e.printstacktrace (); } }}} String s=NULL; Try { //synchronization method to get the stream returned by the server sideResponsestream Responsestream =http.sendsync (httpmethod.post, url, params); S=responsestream.readstring (); } Catch(Exception e) {e.printstacktrace (); } returns; }
Send a POST request using Xutils, carry JSON and picture binary file data Get server-side return JSON data