1 HTTP
The HTTP protocol is probably the most widely used and most important protocol on the Internet now, and more and more Java applications need to access network resources directly through the HTTP protocol.
While the basic functionality of accessing the HTTP protocol has been provided in the JDK's java.net package, the JDK library itself provides a lack of functionality and flexibility for most applications. HttpClient is used to provide efficient, up-to-date, feature-rich client programming toolkits that support the HTTP protocol, and it supports the latest versions and recommendations of the HTTP protocol.
In general, we use Chrome or another browser to access a Web server, to browse the page to view information or submit some data, file upload download and so on. Some of the pages visited are just plain pages, some require users to log in to use them, or require authentication and are transmitted in encrypted form, such as HTTPS. The browsers we use today are not going to pose a problem with these situations. But once we have the need to access the server's resources without a browser? What should we do then?
The following is a local client-initiated file upload, download as an example to do a small demo. There are two forms of httpclient, one is org.apache.http and the other is org.apache.commons.httpclient.HttpClient.
2 File Upload
File upload can be implemented in two ways, one is Postmethod, and the other is HttpPost mode. The processing of the two is similar. Postmethod is to wrap the file wrapper stream using Filebody, HttpPost is to wrap the file stream using Filepart. When you pass a file stream to the server, you can pass other parameters at the same time.
2.1 Client-side processing 2.1.1 Postmethod mode
The file is encapsulated into the filepart, put into the part array, and other parameters can be put into the stringpart, here is not written, just simply set the parameters in Setparameter way. The httpclient here is org.apache.commons.httpclient.HttpClient.
1 public void Upload (String localfile) {2 File File = new file (localfile); 3 Postmethod filepost = new Po Stmethod (URL_STR); 4 HttpClient client = new HttpClient (); 5 6 try {7//The following method can simulate the page parameter submission 8 filepost.setparameter ("UserName", UserName); 9 Filepost.setparameter ("passwd", passwd), ten part[] parts = {New Filepart (File.getname (), file) };12 filepost.setrequestentity (New multipartrequestentity (Parts, Filepost.getparams ())); 13 14 Client.gethttpconnectionmanager (). Getparams (). Setconnectiontimeout (+); int status = Client.executemethod (FilePost); if (status = = Httpstatus.sc_ok) {System.out.println ("Upload Success "); else {System.out.println (" Upload failed ");}22} catch (Exception ex {Ex.printstacktrace ();} finally {filEpost.releaseconnection (); 26}27}
Remember to release the connection via releaseconnection when you're done.
2.1.2 HttpPost Way
This way, similar to the above, just became filebody. The above part array corresponds to httpentity here. The httpclient here are under Org.apache.http.client.methods.
1 public void Upload (String localfile) {2 closeablehttpclient httpClient = null; 3 closeablehttpresponse Response = NULL; 4 try {5 httpClient = Httpclients.createdefault (); 6 7//pass a common parameter and file to the following place Address is a servlet 8 httppost httppost = new HttpPost (URL_STR); 9 10//convert file to stream object FileBody11 filebody bin = new Filebody (new file (LocalFile)); 12 13 Stringbody userName = new Stringbody ("Scott", Contenttype.create "Text/plain", consts.utf_ 8)); Stringbody password = new Stringbody ("123456", Contenttype.create ("Text/plain", Consts.utf_8)); Httpentity reqentity = multipartentitybuilder.create () 19///equivalent to <in Put type= "file" name= "file"/>20. Addpart ("file", bin) 21 22 Equivalent to <input type= "text" name= "UserName" value=username>23. Addpart ("UserName", UserName) Addpart ("Pass", password) 25 . build (); httppost.setentity (reqentity); 28 29//Initiate the request and return the requested response (response = Httpclient.execute (HttpPost); System.out.println ("The response value of token:" + response.g Etfirstheader ("token")); 33 34//Get Response object httpentity resentity = Response.getentit Y (); resentity = null) {37//Print response length System.out.println ("Response con Tent Length: "+ resentity.getcontentlength ()); 39//Print response content (SYSTEM.OUT.PRINTLN) (Entityuti Ls.tostring (resentity, Charset.forname ("UTF-8")); 41}42 43//Destroy the Entity Utils.consume (resentity);}catch (Exception e) {e.printstacktrace ();}finally {48 try {49 if (response! = null) {response.close ();}52} catch (IOException e) {e.printstacktrace ();}55-try {HTTPC Lient! = null) {httpclient.close ();}60} catch (IOException e) {61 E.printstacktrace (); 62}63}64}
2.2 Service-side processing
Regardless of the client is the type of upload, the service side of the processing is the same. After the parameters are obtained by httpservletrequest, the resulting item is categorized into a regular form and a file form.
The size and encoding format of the uploaded file can be set by Servletfileupload.
In short, the processing of the server is to treat the resulting parameters as an HTML form.
1 public void Processupload (HttpServletRequest request, httpservletresponse response) {2 File uploadfile = new Fi Le (Uploadpath); 3 if (!uploadfile.exists ()) {4 uploadfile.mkdirs (); 5} 6 7 System.out.println ("Come On, baby ... "); 8 9 request.setcharacterencoding ("Utf-8"); Ten response.setcharacterencoding ("Utf-8"); 11 12//detection is not present upload file Ismultipart = servletfileupload.ismultipartcontent (request); if (Ismultipart) {Diskfileitemfactory factory = new Diskfileitemfactory (); 17 18//Specifies the size of the cache data in memory, in bytes, which is set to 1Mb factory.setsizethreshold (1024*1024); 20 21//Set when the file size exceeds the value of Getsizethreshold (), the data is stored in the directory of the hard disk factory.setrepository (" D:\\temp ")); //Create A new file upload handler servletfileupload upload = new ServletFileUpload (Factory); 26 27//Specify the maximum size of a single upload file, in bytes, set to 50Mb Upload.setfilesizemax (50 * 1024 * 1024); 29 30//Specify the total size of multiple files uploaded at once, in bytes, set to 50Mb Upload.setsizemax (50 * 1024 * 1024); Upload.setheaderencoding ("UTF-8"); list<fileitem> items = null; try {37//Resolve request requests in + items = Upload.parserequest (r Equest); (Fileuploadexception e) {e.printstacktrace (); (items!=null) {44//Parse form item Iterator <FileItem> iter = Items.iterator (); Iter.hasnext () {Fileitem item = Iter.next (); 48 49 If it is a normal form attribute, the IF (Item.isformfield ()) {51 Equivalent to the name attribute of input <input type= "text" name= "content" > String name = Item.getfieldname ();//input the Value property in the String value = ITEM.G Etstring (); System.out.println ("attribute:" + name + "attribute value:" + value); 58} 59//If uploading a file, or {61//property The name of the String fieldName = Item.getfieldname (); 63 64//upload file path. String fileName = Item.getname ( ); filename.substring filename = filename.lastindexof ("/") + 1);//Get the file name of the upload 67 Item.write (New File (Uploadpath, fileName)); (Exception e) {71} E.printstacktrace (); 72} 73} 74} 75} 76} 77 78 Response.AddHeader ("token", "Hello"); 79}
After the server is processed, you can set up simple information returned to the client in the header. If the return client is a stream, the size of the stream must be set in advance!
Response.setcontentlength ((int) file.length ());
3 File Download
The download of the file can be implemented using the HttpClient GetMethod, and you can use the HttpGet method and the original HttpURLConnection method.
3.1 Client-side processing 3.1.1 GetMethod mode
The httpclient here is org.apache.commons.httpclient.HttpClient.
1 public void DownLoad (string remotefilename, String localfilename) {2 HttpClient client = new HttpClient (); 3 GetMethod get = null; 4 FileOutputStream output = null; 5 6 try {7 get = new GetMethod (URL_STR); 8 Get.setrequestheader ("UserName", user Name); 9 Get.setrequestheader ("passwd", passwd), Get.setrequestheader ("FileName", remotefilename); 11 12 int i = Client.executemethod (get), if (SUCCESS = = i) {System.out.println ( "The response value of token:" + get.getresponseheader ("token")); file StoreFile = new file (localfile Name); output = new FileOutputStream (storefile); 19 20//Gets a byte array of network resources and writes File Output.write (Get.getresponsebody ()); else {System.out.println ("Dow Nload file occurs exception, the error code is: "+ i); 24 }25} catch (Exception e) {e.printstacktrace ();} finally {29 if (output! = null) {output.close ();}32} catch (Ioexceptio n e) {e.printstacktrace ();}35 get.releaseconnection (); 37 Client.gethttpconnectionmanager (). closeidleconnections (0); 38}39}
3.1.2 HttpGet Way
The httpclient here are under Org.apache.http.client.methods.
1 public void DownLoad (string remotefilename, String localfilename) {2 Defaulthttpclient httpClient = new Defaul Thttpclient (); 3 OutputStream out = null; 4 InputStream in = null; 5 6 try {7 HttpGet httpget = new HttpGet (URL_STR); 8 9 Httpget.addheader ("UserN Ame ", userName); Httpget.addheader (" passwd ", passwd); Httpget.addheader (" FileName ", RemoteFile Name); HttpResponse HttpResponse = Httpclient.execute (httpget); httpentity entity = Httpres Ponse.getentity (); Entity.getcontent (); 18 Long length = Entity.getcontentlength (); if (length <= 0) {System.out.println ("Download file does not exist!) "); return;21}22 System.out.println (" The response value of token: "+ httpres Ponse.getfirstheader ("token")); file File = new file (LocalFilename);. Exists ()) {file.createnewfile ();}29-out = new Fileoutputstrea m (file); byte[] buffer = new BYTE[4096];32 int readlength = 0;33 while ((Readlength=in.read ( Buffer)) > 0) {byte[] bytes = new byte[readlength];35 system.arraycopy (buffer, 0, by TES, 0, Readlength), Out.write (bytes), PNs}38 Out.flush (); 40 (IOException e) {E.printstacktrace (); (Exception e) {e.printstacktrace ();}final ly{46 try {in.close (in! = null) {in. 49}50 } catch (IOException e) {e.printstacktrace ();}53 try {55 if (out! = null) {out.close (); 57}58 } catch (IOException e) {e.printstacktrace (); 60}61}62}
3.1.3 HttpURLConnection Way
1 public void Download3 (string remotefilename, String localfilename) {2 FileOutputStream out = null; 3 I Nputstream in = null; 4 5 try{6 url url = new URL (url_str); 7 URLConnection urlconnection = Url.openco Nnection (); 8 HttpURLConnection httpurlconnection = (httpurlconnection) urlconnection; 9//True--would setting PARAMETERS11 Httpurlconnection.setdooutput (true); 12 True--will allow read in From13 Httpurlconnection.setdoinput (true); Ches15 httpurlconnection.setusecaches (FALSE);//Setting Serialized17 Httpurlconnect Ion.setrequestproperty ("Content-type", "application/x-java-serialized-object");//default is GET Httpurlconnection.setrequestmethod ("POST"); httpurlconnection.setrequestproperty ("Connection", "Keep-alivE "); Httpurlconnection.setrequestproperty (" Charsert "," UTF-8 "); 1 min23 Httpurl Connection.setconnecttimeout (60000); 1 min25 httpurlconnection.setreadtimeout (60000); 26 27 Httpurlconnection.addrequestproperty ("UserName", UserName); Httpurlconnection.addrequestproperty (" passwd ", passwd); Httpurlconnection.addrequestproperty (" FileName ", remotefilename);//Conn ECT to Server (TCP) + Httpurlconnection.connect (); in = Httpurlconnection.getinputstream ();// Send request TO35//server36 File File = new File (localfilename), PNs if (!file.exists ()) {file.createnewfile (); 39}40 41 out = new FileOutputStream (file); byte[] buffer = new byte[4096];43 int readlength = 0;44 while (rEadlength=in.read (buffer)) > 0) {byte[] bytes = new byte[readlength];46 System.Array Copy (buffer, 0, bytes, 0, readlength), Out.write (bytes),}49 ou T.flush (); Wuyi}catch (Exception e) {e.printstacktrace ();}finally{54 try {55 if (in = null) {in.close ();}58} catch (IOException e) { E.printstacktrace ();}61. try {if (out! = nul L) {out.close ();}66} catch (IOException e) {E.pri Ntstacktrace (); 68}69}70}
3.2 Service-side processing
Although the client is handled differently, the server is the same.
1 public void Processdownload (HttpServletRequest request, httpservletresponse response) {2 int buffer_size = 4096 ; 3 InputStream in = null; 4 OutputStream out = null; 5 6 System.out.println ("Come on, baby ....."); 7 8 try{9 request.setcharacterencoding ("Utf-8"); Ten response.setcharacterencoding ("Utf-8"); Response.setcontenttype ("Application/octet-stream"); String userName = Request . GetHeader ("UserName"); string passwd = Request.getheader ("passwd"); string fileName = Request . GetHeader ("FileName"), System.out.println ("UserName:" + userName), System.out. println ("passwd:" + passwd), System.out.println ("filename:" + filename), 20 21//Can be based on Username and passwd are passed for further processing, such as verifying that the request is legitimate, such as the file File = new file (Downloadpath + "\ \" + fileName);Response.setcontentlength ((int) file.length ()); Response.setheader ("accept-ranges", "bytes"); readlength int = 0;28 in = new Bufferedinputstream (New fileinputs Tream (file), buffer_size); out = new Bufferedoutputstream (Response.getoutputstream ()); 31 32 byte[] buffer = new byte[buffer_size];33 while ((Readlength=in.read (buffer)) > 0) {34 byte[] bytes = new byte[readlength];35 system.arraycopy (buffer, 0, bytes, 0, readlength); 36 Out.write (bytes), Panax Notoginseng}38 Out.flush (); Header ("token", "Hello 1"),}catch (Exception e) {e.printstacktrace (); 45 Response.AddHeader ("token", "Hello 2");}finally {if (in! = NULL) {$ try {49 In.cLose (); IOException catch (E) {}52}53 if (out! = null) {54 try {out.close (); d} catch (IOException e) {57}5 8}59}60}
4 Summary
The most basic function of httpclient is to execute the HTTP method. The execution of an HTTP method involves the interaction of one or more HTTP request/http responses, which is usually handled automatically by httpclient and transparently to the user. The user only needs to provide the HTTP request object, HttpClient sends the HTTP request to the target server and receives the server's response, and HttpClient throws an exception if the HTTP request execution is unsuccessful. So when you write code, pay attention to the finally processing.
All HTTP requests have a request line, including the method name, the requested URI, and the HTTP version number. HttpClient supports http/1.1 all HTTP methods defined by this version: Get,head,post,put,delete,trace and options. The upload above is used for post, and the download is get.
For now, use org.apache.commons.httpclient.HttpClient more. Look at yourself ~
Uploading and downloading files using httpclient