The solution to HttpClient uploading Chinese garbled characters is as follows,
Anyone who has used HttpClient knows that you can use the addTextBody method to add text information to be uploaded. However, if you want to upload Chinese text or files with Chinese names, garbled characters may occur, the solution is actually very simple:
Step 1: Set the encoding method of MultipartEntityBuilder to UTF-8.
Builder. setCharset (Charset. forName (HTTP. UTF_8); // you can specify the Request Encoding format.
Step 2: Create a ContentType object that specifies the UTF-8 encoding.
ContentType contentType= ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
Step 3: Use addPart + StringBody to replace addTextBody. For example:
StringBody stringBody = new StringBody ("Chinese Garbled text", contentType); builder. addPart ("test", stringBody );
Complete code is attached:
ContentType contentType = ContentType. create (HTTP. PLAIN_TEXT_TYPE, HTTP. UTF_8); HttpClient client = new DefaultHttpClient (); // enable a client HTTP request HttpPost post = new HttpPost (url); // create an http post request MultipartEntityBuilder builder = MultipartEntityBuilder. create (); builder. setCharset (Charset. forName (HTTP. UTF_8); // sets the Request Encoding format builder. setMode (HttpMultipartMode. BROWSER_COMPATIBLE); // sets the browser compatibility mode int count = 0; for (File file: files) {// FileBody fileBody = new FileBody (file ); // convert the file into a stream object FileBody // builder. addPart ("file" + count, fileBody); builder. addBinaryBody ("file" + count, file); count ++;} builder. addTextBody ("method", params. get ("method"); // sets the request parameter builder. addTextBody ("fileTypes", params. get ("fileTypes"); // set the request parameter StringBody stringBody = new StringBody ("Chinese Garbled text", contentType); builder. addPart ("test", stringBody); HttpEntity entity = builder. build (); // generate an http post object post. setEntity (entity); // set the request parameter HttpResponse response = client.exe cute (post); // initiate the request and return the request response if (response. getStatusLine (). getStatusCode () = 200) {return true;} return false;