1. Reliance
The request to impersonate the HTTP port relies on Apache HttpClient, requires third-party JSON support, and the project adds
<dependency> <groupId>org.apache</groupId> <artifactid>httpclient</ artifactid> <version>4.1.2</version> </dependency>
<dependency> <groupId>org.apache</groupId> <artifactid>httpclient</ Artifactid> <version>4.1.2</version></dependency>
2. Source code
ImportOrg.apache.commons.httpclient.HttpStatus;Importorg.apache.http.HttpEntity;ImportOrg.apache.http.HttpResponse;Importorg.apache.http.client.HttpClient;ImportOrg.apache.http.client.methods.HttpPost;Importorg.apache.http.entity.mime.MultipartEntity;ImportOrg.apache.http.entity.mime.content.InputStreamBody;ImportOrg.apache.http.entity.mime.content.StringBody;Importorg.apache.http.impl.client.DefaultHttpClient;Importorg.apache.http.util.EntityUtils;ImportOrg.json.JSONObject;ImportJava.io.*;Importjava.net.HttpURLConnection;ImportJava.net.URL;/*** Created by Administrator on 2016/1/19.*/ Public classFileuploadtest { Public Staticstring Upload (string url,string filePath) {string Fdfspath= ""; Try{HttpClient HttpClient=Newdefaulthttpclient ();//HttpPost httppost = new HttpPost ("http://127.0.0.1: 8082/fileupload.action ");//Request FormatHttpPost HttpPost =Newhttppost (URL); File File=NewFile (FilePath); String name=File.getname (); InputStream in=Newfileinputstream (file); Multipartentity reqentity=Newmultipartentity (); Inputstreambody Inputstreambody=Newinputstreambody (in,name); Stringbody Filenam=Newstringbody (name); Reqentity.addpart ("UploadFile", Inputstreambody); Reqentity.addpart ("Uploadfilename", Filenam); Httppost.setentity (reqentity); HttpResponse Response=Httpclient.execute (HttpPost); intStatusCode =response.getstatusline (). Getstatuscode (); if(StatusCode = =HTTPSTATUS.SC_OK) {//System.out.println ("Server normal response .....");Httpentity resentity =response.getentity (); Jsonobject JSON=NewJsonobject (entityutils.tostring (resentity). toString ()); System.out.println (Json.getstring ("Returnresult"));//System.out.println (entityutils.tostring (resentity));//HttpClient comes with the tool class to read the returned data//System.out.println (Resentity.getcontent ());Entityutils.consume (resentity); } } Catch(Exception e) {e.printstacktrace (); } return""; } }
3. Parsing
Upload parameters: url--Upload server-side interface request, FilePath---Local file or picture storage path.
Java analog HTTP request upload file, based on Apache HttpClient