Use httpclient Multipartentitybuilder to upload files and solve Chinese file name garbled problem

Source: Internet
Author: User
Tags getmessage parse error

When a business scenario is encountered, the front-end uploaded files need to be forwarded through the Java service to the file service. During the encounter of the original httpclient how to use the problem, how to multipartfile how to re-assemble the HTTP request sent out the problem, file Chinese name garbled problem. Finally all solved, first on the code, then talk about the hole encountered

1 @Slf4j2 @Service3  Public classFileserviceimplImplementsIfileservice {4 5@Value ("${fileservice.puturl}")6     PrivateString Puturl;7@Value ("${fileservice.app_id}")8     PrivateString appId;9@Value ("${fileservice.securitykey}")Ten     PrivateString SecureKey; One  A     Private Final StaticString Upload_response_code = "Error"; -     Private Final StaticInteger upload_response_success = 0; -  the  - @Override -      PublicString Upload (multipartfile file) { -  +         intTimeOut = 30000; -Closeablehttpclient httpClient =httpclientbuilder.create (). build (); +Httphost proxy =NewHttphost ("127.0.0.1", 62145, "http");//set up local fiddler agent for Easy Troubleshooting ARequestconfig Requestconfig =Requestconfig.custom (). Setconnectionrequesttimeout (TimeOut) at . Setconnecttimeout (timeout). SetSocketTimeout (timeout). SetProxy (proxy). build (); -HttpPost HttpPost =NewHttpPost (puturl); - Httppost.setconfig (requestconfig); -         Try { -             //browser_compatible Custom Charset,rfc6532=utf-8,strict=iso-8859-1 -             //here must use RFC6532, online commonly used browser_compatible will still appear Chinese name garbled inMultipartentitybuilder Multipartentitybuilder =multipartentitybuilder.create (). SetMode (httpmultipartmode.rfc6532); -             //Multipartentitybuilder.setcharset (Charset.forname ("UTF-8"));//Here the pit, the forward filename is still garbled to            //ContentType ContentType = contenttype.create ("Multipart/form-data", Charset.forname ("UTF-8"));//Here is also the pit, the forward filename is still garbled +Multipartentitybuilder.addbinarybody ("File", File.getinputstream (), Contenttype.default_binary, File.getoriginalfilename ()); -  theMultipartentitybuilder.addtextbody ("app_id", appId);//you can replace them with additional fields you need. *             LongTime = System.currenttimemillis ()/1000; $Multipartentitybuilder.addtextbody ("Time", string.valueof (time));//you can replace them with additional fields you need.Panax NotoginsengString beforesign = String.Format ("app_id=%s&time=%s%s", AppId, Time, SecureKey); -String sign =md5util.md5 (beforesign); theMultipartentitybuilder.addtextbody ("sign", sign);//you can replace them with additional fields you need. +  AHttpentity requestentity =multipartentitybuilder.build (); the httppost.setentity (requestentity); +HttpResponse HttpResponse =Httpclient.execute (httppost); -             intStatuscode=httpresponse.getstatusline (). Getstatuscode (); $             if(StatusCode! = 200)Throw NewBizexception (Bizcode.inner_service_error, "Response status code:" +statusCode); $Httpentity responseentity =httpresponse.getentity (); -             returngeturlstring (entityutils.tostring (responseentity)); -}Catch(Exception e) { theLog.error ("Send file exception: {}", e); -             Throw NewBizexception (Bizcode.inner_service_error, "Send file Service exception:" +e.getmessage ());Wuyi}finally { the             Try { - httpclient.close (); Wu}Catch(IOException e) { -Log.error ("Close HttpClient exception:" +e.getmessage (), e); About             } $         } -     } -  -     Privatestring geturlstring (String jsonstring) { A         Try{ +Log.debug ("Parse JSON string:" +jsonstring); theJsonobject Jsonobject =Jsonobject.parseobject (jsonstring); -             if(Jsonobject.getinteger (upload_response_code)! =upload_response_success) { $Log.error ("File service returned error:" + jsonobject.getstring ("Data")); the                 Throw NewOtherservicereturnerrorexception ("File service returned error:" + jsonobject.getstring ("Data")); the             } the             return((Jsonobject) jsonobject.get ("Data")). Get ("original")). toString (); the}Catch(Exception e) { -Log.error ("File service returned JSON parse error:" +jsonstring); in             Throw NewOtherservicereturnerrorexception ("File service returned JSON parse error:" +jsonstring); the         } the  About     } the}

Special notes and encounters with pits:

1. For request forwarding based on Tomcat, you need to manually add the proxy in your code:

Httphost proxy = new Httphost ("127.0.0.1", 62145, "http"); Set up local fiddler agent for Easy troubleshooting
Requestconfig requestconfig = Requestconfig.custom (). Setconnectionrequesttimeout (TimeOut)
. Setconnecttimeout (Timeout). SetSocketTimeout (timeout). SetProxy (proxy). Build ();

2. Multipartfile through getInputStream () can set the flow to Multipartentitybuilder, where contenttype and filename inside the addbinarybody must be set, Otherwise the subsequent service cannot read this file stream

Multipartentitybuilder Multipartentitybuilder = Multipartentitybuilder.create (). SetMode (HttpMultipartMode.RFC6532 );
Multipartentitybuilder.addbinarybody ("File", File.getinputstream (), contenttype.default_binary, File.getoriginalfilename ());

3. The File.getoriginalfilename () method is not garbled, but after addbinarybody, the assembled HTTP request is always garbled, such as:

Stepping on a variety of pits, such as set charset for Multipartentitybuilder or manually set contenttype, can not solve the problem, the file name is still shown garbled

It was later found that setting mode to httpmultipartmode.rfc6532 in Multipartentitybuilder perfectly solves this problem and no longer requires the ContentType or charset to be set separately, Because httpmultipartmode.rfc6532 told the Multipartentitybuilder, the data inside the use of UTF-8 to deal with, Fiddler caught the request found that filename successfully became Chinese name.

Done

Use httpclient Multipartentitybuilder to upload files and solve Chinese file name garbled problems

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.