About HttpClient upload Chinese garbled solution

Source: Internet
Author: User
Tags http post

People who have used HttpClient know that you can add text information to upload by addtextbody method, but if you want to upload Chinese, or if you have a Chinese name file, the problem is garbled, the solution is simple:

The first step: Set the multipartentitybuilder encoding method to UTF-8.


Step Two: Create the ContentType object and specify the UTF-8 encoding.

Step three: Use addpart+stringbody instead of addtextbody. Such as:

Stringbody stringbody=new stringbody ("Chinese garbled", contentType); Builder.addpart ("Test", stringbody);

Enclose the complete code:

ContentType ContentType = Contenttype.create (HTTP. Plain_text_type, HTTP.      UTF_8); HttpClient client=new defaulthttpclient ();//Open a client http request HttpPost post = new HttpPost (URL);//Create an HTTP POST request Multipar Tentitybuilder builder = multipartentitybuilder.create (); Builder.setcharset (Charset.forname (HTTP. Utf_8));//Set the requested encoding format Builder.setmode (httpmultipartmode.browser_compatible);//Set browser compatibility mode int count=0;for (file file: files) {//filebody filebody = new Filebody (file);//convert file to stream object Filebody//builder.addpart ("file" +count, filebody); Builder.addbinarybody ("File" +count, file); count++;} Builder.addtextbody ("Method", Params.get ("method"));//Set request parameter Builder.addtextbody ("FileTypes", Params.get (" FileTypes "));//Set request parameter Stringbody stringbody=new stringbody (" garbled ", ContentType); Builder.addpart (" Test ", Stringbody) ; httpentity entity = Builder.build ();//Generate HTTP POST entity post.setentity (entity);//Set request parameter HttpResponse response = Client.exec Ute (POST);//initiate the request and return the requested response if (Response.getstatusline (). Getstatuscode () ==200) {return true;} return false;


About HttpClient upload Chinese garbled solution

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.