Today in the media upload download interface, regardless of which API can not submit the correct data submitted in the past, not connected to the server, that is, the server returned data errors, backstage Baidu, find an article, but not with httpclient written, he is directly with the JDK with the URLConnection the submitted data. At first glance, think of httpclient should also be able to do, also modeled under that buddies assembled under the data to try, with stringentity,fileentity,inputstreamentity data is not submitted correctly. Then went out to smoke a cigarette, to clarify the idea. Rewrite came, the results have succeeded, the specific combination of the following code analysis.
- The following code submits a POST request to the server using the HttpClient code.
/*** HttpClient POST request, upload multimedia file * *@paramURL * Request Address *@paramparams * parameter list *@returnResponse String *@throwsunsupportedencodingexception * @Author Jie * @Date 2015-2-12*/ Public Staticstring postMethod2 (string url, string filePath) {Log.info ("------------------------------HttpClient post start-------------------------------"); Log.info ("POST:" +URL); Log.info ("FilePath:" +FilePath); if(Stringutils.isblank (URL)) {Log.error ("The POST request is not valid, please check the URI parameter!"); return NULL; } StringBuilder Content=NewStringBuilder (); //simulate a form to upload a POST submission body contentString boundary = "-----------------------------" +NewDate (). GetTime (); //files to uploadFile File =NewFile (FilePath); if(!file.exists () | |file.isdirectory ()) {Log.error (FilePath+ ": Not a valid file path"); return NULL; } //Response ContentString respcontent =NULL; InputStream is=NULL; OutputStream OS=NULL; File Tempfile=NULL; Closeablehttpclient httpClient=NULL; HttpPost HttpPost=NULL; Try { //Create temporary file, save post content to the temporary file, temporary file saved in system default temp directory, use system default file nameTempfile = File.createtempfile (NewSimpleDateFormat ("Yyyy_mm_dd"). Format (NewDate ()),NULL); OS=NewFileOutputStream (tempfile); is=Newfileinputstream (file); Os.write (("--" + boundary + "\ r \ n"). GetBytes ()); Os.write (String.Format ("Content-disposition:form-data; Name=\ "Media\"; Filename=\ "" + file.getname () + "\" \ "\ \ \ \"). GetBytes ()); Os.write (String.Format ("Content-type:%s\r\n\r\n", Fileutils.getmimetype (file)). GetBytes ()); //Read upload fileBufferedinputstream bis =NewBufferedinputstream (IS); byte[] Buff =New byte[8096]; intLen = 0; while(len = bis.read (buff))! =-1) {os.write (buff,0, Len); } os.write (("\r\n--" + boundary + "--\r\n"). GetBytes ()); HttpClient=Httpclients.createdefault (); //Create a POST requestHttpPost =Newhttppost (URL); //Create a request entityFileentity reqentity =Newfileentity (Tempfile, contenttype.multipart_form_data); //Set Request EncodingReqentity.setcontentencoding ("UTF-8"); Httppost.setentity (reqentity); //Execute RequestHttpResponse response =Httpclient.execute (HttpPost); //Get Response ContentRespcontent = repsonse (content, Response, "POST"); } Catch(clientprotocolexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } finally { Try{Close (tempfile, OS, is, HttpPost, httpClient); } Catch(IOException e) {e.printstacktrace (); }} log.info ("Respone:" +respcontent); Log.info ("------------------------------HttpClient post End-------------------------------"); returnrespcontent; }
- The following code is to get the server corresponding content.
/*** Get response content for MimeType for Text/plan, text/json format * *@paramContent * Response Contents *@paramResponse * HttpResponse Object *@paramMethod * Request Method get| POST *@returnstring converted to UTF-8 *@throwsParseException *@throwsIOException * @Author Jie * @Date 2015-2-28*/ Private StaticString Repsonse (StringBuilder content, HttpResponse response, string method)throwsParseException, IOException {statusline statusline=Response.getstatusline (); intStatusCode = Statusline.getstatuscode ();//Response CodeString reasonphrase = Statusline.getreasonphrase ();//Response Information if(StatusCode = = 200) {//Request succeededhttpentity entity =response.getentity (); Log.info ("Minetype:" +Entity.getcontenttype (). GetValue ()); Content.append (Entityutils.tostring (entity)); } Else{Log.error (method+ ": code[" + StatusCode + "],desc[" + Reasonphrase + "]"); } return NewString (Content.tostring (). GetBytes ("Iso8859-1"), "UTF-8"); }
Summary: Finally used fileentity This request entity, successfully uploaded multimedia files to the server, to obtain the server returned MEDIA_ID. Interface is implemented, but always feel where there is something to improve.
HttpClient Uploading Files