HTTP Post Upload general method, support text, pictures, files and so on.
Dependent jar package: http://hc.apache.org/downloads.cgi Download httpclient * * * * Binary.
Copy the Httpmime-4.3.3.jar from the Httpcomponents libraries to the Libs of your Android project.
Populate an uploaded entity object
multipartentity entity =Newmultipartentity (httpmultipartmode.browser_compatible);
Entity.addpart ("String", NewStringbody ("String", Charset.forname ("UTF-8")) ; Entity.addpart ("File", NewFilebody (NewFile ("path")); /Call post method to upload
Httptools.post ("url", entity)//http upload generic method class
Public classHttptools { Public Static Final intHttp_success = 200; Private StaticString response_string =NULL; Private StaticJsonobject Response_json =NULL;
......
...... Public Static Booleanpost (String URL, multipartentity entity) {Try{HttpClient HttpClient=Newdefaulthttpclient (); HttpContext Localcontext=NewBasichttpcontext (); HttpPost HttpPost=NewHttpPost (Server_addr +URL); Httppost.setentity (entity); HttpResponse Response=Httpclient.execute (HttpPost, Localcontext); if(Response.getstatusline (). Getstatuscode () = =http_success) {response_string=entityutils.tostring (Response.getentity ()); Response_json=NewJsonobject (response_string); return true; } } Catch(clientprotocolexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(jsonexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } return false; } ......
...}
About uploading text garbled situation Description:
No text encoding was previously set
Entity.addpart ("string", new stringbody ("string"));
Uploading text directly will be garbled.
in Android development, When submitting Chinese data to the server in HttpPost mode, data obtained on the service side will be garbled if the encoding type of the transmitted data is not set. In the application involving different platforms, we try to transfer Chinese data using UTF-8 encoding format, HttpPost mode transfer Chinese specified encoding can refer to the following methods:
Entity.addpart ("String" new stringbody ("String", Charset.forname ("UTF-8"