1 HTTP
The HTTP protocol is probably the most frequently used and important protocol on the Internet today, and more and more Java applications need to access network resources directly through the HTTP protocol.
Although the basic functionality of accessing the HTTP protocol has been provided in the JDK's java.net package, the JDK library itself offers not enough functionality and flexibility for most applications. HttpClient is used to provide efficient, up-to-date, feature-rich client-side programming kits that support HTTP protocols, and it supports the latest versions and recommendations of the HTTP protocol.
In general, we use chrome or other browsers to access a Web server that browses the page to view information or submit data, upload downloads, and so on. Some of the pages visited are just plain pages, some need to be logged in before they can be used, or they need to be authenticated and are transmitted via encryption, such as HTTPS. Currently, the browsers we use to handle these situations do not pose a problem. But once we have the need to access the server's resources without using the browser? So what should we do?
Below the local client launch file upload, download as an example to do a small demo. There are two forms of httpclient, one is Org.apache.http, the other is org.apache.commons.httpclient.HttpClient.
2 File Upload
File upload can be implemented in two ways, one is Postmethod way, the other is HttpPost way. The treatment of the two is very similar. Postmethod is to use Filebody to wrap the file wrapper flow, HttpPost to use Filepart to wrap the file flow. Other parameters can be passed at the same time when the file stream is passed to the server.
2.1 Client Processing
2.1.1 Postmethod mode
Encapsulate the file into Filepart, put it into the part array, while other parameters can be placed in the Stringpart, not written here, but simply set the parameters in a setparameter way. The httpclient here is org.apache.commons.httpclient.HttpClient.
public void Upload (String localfile) {
File File = new file (localfile);
Postmethod filepost = new Postmethod (URL_STR);
HttpClient client = new HttpClient ();
try {
///Can simulate page parameter submission
filepost.setparameter ("UserName", UserName) by the following methods;
Filepost.setparameter ("passwd", passwd);
part[] Parts = {New Filepart (File.getname (), file)};
Filepost.setrequestentity (New multipartrequestentity (Parts, Filepost.getparams ()));
Client.gethttpconnectionmanager (). Getparams (). Setconnectiontimeout (5000);
int status = Client.executemethod (FilePost);
if (status = = Httpstatus.sc_ok) {
System.out.println ("Upload succeeded");
} else {
System.out.println ("Upload failed");
} The
catch (Exception ex) {
ex.printstacktrace ();
} finally {
filepost.releaseconnection ();
}
}
Remember to release the connection via releaseconnection after you finish.
2.1.2 HttpPost Mode
This way, similar to the above, but become a filebody. The part array above corresponds to httpentity here. The httpclient here are org.apache.http.client.methods.
public void Upload (String localfile) {closeablehttpclient httpclient = null;
Closeablehttpresponse response = null;
try {httpclient = Httpclients.createdefault ();
To pass an ordinary parameter and file to the following address is a servlet httppost httppost = new HttpPost (URL_STR);
Convert file to stream object Filebody filebody bin = new Filebody (new file (LocalFile));
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 ()//equivalent to <input type= "file" name= "file"/>. A Ddpart ("File", bin)//corresponds to the <input type= "text" name= "UserName" value=username>. Addpart
("UserName", UserName). Addpart ("Pass", password). build ();
Httppost.setentity (reqentity); Initiates a request and returns a response to the request ResponSE = Httpclient.execute (httppost);
SYSTEM.OUT.PRINTLN ("The response value of token:" + response.getfirstheader ("token"));
Gets the response object httpentity resentity = Response.getentity (); if (resentity!= null) {//Print response length System.out.println ("Response Content Length:" + resentity.getcontentle
Ngth ());
Print the response content System.out.println (entityutils.tostring (resentity, Charset.forname ("UTF-8"));
}//Destroy Entityutils.consume (resentity);
}catch (Exception e) {e.printstacktrace ();
}finally {try {if (response!= null) {response.close ();
} catch (IOException e) {e.printstacktrace ();
try {if (httpclient!= null) {httpclient.close ();
} catch (IOException e) {e.printstacktrace (); }
}
}
2.2 Service-side processing
Regardless of the client is the way to upload, server processing is the same. After you get the parameters through HttpServletRequest, you categorize the resulting item into common forms and file forms.
You can set the size and encoding format of the uploaded file by servletfileupload.
In short, the service-side processing is to treat the resulting parameters as HTML forms.
public void Processupload (HttpServletRequest request, httpservletresponse response) {File uploadfile = new File (Uploa
Dpath);
if (!uploadfile.exists ()) {uploadfile.mkdirs ();
} System.out.println ("Come on, Baby ...");
Request.setcharacterencoding ("Utf-8");
Response.setcharacterencoding ("Utf-8");
Detect if there is an upload file Boolean ismultipart = servletfileupload.ismultipartcontent (request);
if (Ismultipart) {Diskfileitemfactory factory = new Diskfileitemfactory ();
Specifies the size of the data to be cached in memory, in bytes, which is set to 1Mb factory.setsizethreshold (1024*1024);
Set the directory factory.setrepository (new file ("D:\\temp") that the data is stored on the hard disk once the file size exceeds the value of Getsizethreshold ();
Create a new file upload handler servletfileupload upload = new Servletfileupload (factory);
Specifies the maximum size, in bytes, of a single uploaded file, set to 50Mb Upload.setfilesizemax (50 * 1024 * 1024); Specify the total size, in bytes, of multiple files uploaded at a time, set to 50Mb upload. Setsizemax (50 * 1024 * 1024);
Upload.setheaderencoding ("UTF-8");
list<fileitem> items = null;
try {//Parse request Requests items = Upload.parserequest (request);
catch (Fileuploadexception e) {e.printstacktrace ();
} if (Items!=null) {//Parse form item iterator<fileitem> ITER = Items.iterator ();
while (Iter.hasnext ()) {Fileitem item = Iter.next ();
If the normal form property if (Item.isformfield ()) {//corresponds to the Name property of input <input type= "text" name= "Content" >
String name = Item.getfieldname ();
Input's Value property String value = Item.getstring ();
System.out.println ("Property: + Name +" Property value: + value);
//If upload file else {//property name String FieldName = Item.getfieldname ();
Upload file path String fileName = Item.getname ();
filename = filename.substring (Filename.lastindexof ("/") + 1)//Get uploaded file filename try {
Item.write (New File (Uploadpath, fileName));
catch (Exception e) {e.printstacktrace ();
}}} Response.AddHeader ("token", "Hello"); }
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 Downloads
The download of the file can be implemented using the HttpClient GetMethod, as well as using the HttpGet method, the original HttpURLConnection method.
3.1 Client Processing
3.1.1 GetMethod mode
The httpclient here is org.apache.commons.httpclient.HttpClient.
public void DownLoad (string remotefilename, String localfilename) {httpclient client = new HttpClient ();
GetMethod get = null;
FileOutputStream output = null;
try {get = new GetMethod (URL_STR);
Get.setrequestheader ("UserName", userName);
Get.setrequestheader ("passwd", passwd);
Get.setrequestheader ("FileName", remotefilename);
int i = Client.executemethod (get);
if (SUCCESS = i) {System.out.println ("The response value of token:" + get.getresponseheader ("token"));
File StoreFile = new file (LocalFilename);
Output = new FileOutputStream (storefile);
Gets a byte array of network resources and writes to the file Output.write (Get.getresponsebody ());
else {System.out.println ("DownLoad file occurs exception, the error code is:" + i);
} catch (Exception e) {e.printstacktrace ();
Finally {try {if (output!= null) {output.close (); catch (IoexcePtion e) {e.printstacktrace ();
} get.releaseconnection ();
Client.gethttpconnectionmanager (). closeidleconnections (0); }
}
3.1.2 HttpGet Mode
The httpclient here are org.apache.http.client.methods.
public void DownLoad (string remotefilename, String localfilename) {defaulthttpclient httpclient = new DEFAULTHTTPCLI
ENT ();
OutputStream out = null;
InputStream in = null;
try {httpget httpget = new HttpGet (URL_STR);
Httpget.addheader ("UserName", userName);
Httpget.addheader ("passwd", passwd);
Httpget.addheader ("FileName", remotefilename);
HttpResponse HttpResponse = Httpclient.execute (HttpGet);
httpentity entity = httpresponse.getentity ();
in = Entity.getcontent ();
Long length = Entity.getcontentlength (); if (length <= 0) {System.out.println ("Download file does not exist!")
");
Return
} System.out.println ("The response value of token:" + httpresponse.getfirstheader ("token"));
File File = new file (LocalFilename);
if (!file.exists ()) {file.createnewfile ();
out = new FileOutputStream (file);
byte[] buffer = new byte[4096];
int readlength = 0; while ((Readlength=in.read (buffer) > 0) {byte[] bytes = new Byte[readlength];
System.arraycopy (buffer, 0, bytes, 0, readlength);
Out.write (bytes);
} out.flush ();
catch (IOException e) {e.printstacktrace ();
catch (Exception e) {e.printstacktrace ();
}finally{try {if (in!= null) {in.close ();
} catch (IOException e) {e.printstacktrace ();
try {if (out!= null) {out.close ();
} catch (IOException e) {e.printstacktrace (); }
}
}
3.1.3 httpurlconnection
public void Download3 (string remotefilename, String localfilename) {fileoutputstream out = null;
InputStream in = null;
try{url url = new URL (url_str);
URLConnection urlconnection = Url.openconnection ();
HttpURLConnection httpurlconnection = (httpurlconnection) urlconnection;
True--would setting parameters Httpurlconnection.setdooutput (TRUE);
True--will allow read in from Httpurlconnection.setdoinput (true);
Won't use caches httpurlconnection.setusecaches (false); Setting serialized Httpurlconnection.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 min httpurlconnection.setconnecttimeout (60000); 1 min HTTpurlconnection.setreadtimeout (60000);
Httpurlconnection.addrequestproperty ("UserName", userName);
Httpurlconnection.addrequestproperty ("passwd", passwd);
Httpurlconnection.addrequestproperty ("FileName", remotefilename);
Connect to Server (TCP) Httpurlconnection.connect (); in = Httpurlconnection.getinputstream (),//Send request to//server file = new
File (LocalFilename);
if (!file.exists ()) {file.createnewfile ();
out = new FileOutputStream (file);
byte[] buffer = new byte[4096];
int readlength = 0;
while ((Readlength=in.read (buffer) > 0) {byte[] bytes = new Byte[readlength];
System.arraycopy (buffer, 0, bytes, 0, readlength);
Out.write (bytes);
} out.flush ();
}catch (Exception e) {e.printstacktrace ();
}finally{try {if (in!= null) {in.close (); catch (IoexcEption e) {e.printstacktrace ();
try {if (out!= null) {out.close ();
} catch (IOException e) {e.printstacktrace (); }
}
}
3.2 Service-side processing
Although the client handles differently, the service side is the same.
public void Processdownload (HttpServletRequest request, httpservletresponse response) {int buffer_size = 4096;
InputStream in = null;
OutputStream out = null;
System.out.println ("Come on, Baby ...");
try{request.setcharacterencoding ("Utf-8");
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);
Can be further processed according to the username and passwd passed, such as verifying that the request is legitimate, such as file File = new file (Downloadpath + "\" + fileName);
Response.setcontentlength ((int) file.length ());
Response.setheader ("accept-ranges", "bytes");
int readlength = 0; in = new BuFferedinputstream (new FileInputStream (file), buffer_size);
out = new Bufferedoutputstream (Response.getoutputstream ());
byte[] buffer = new Byte[buffer_size];
while ((Readlength=in.read (buffer) > 0) {byte[] bytes = new Byte[readlength];
System.arraycopy (buffer, 0, bytes, 0, readlength);
Out.write (bytes);
} out.flush ();
Response.AddHeader ("token", "Hello 1");
}catch (Exception e) {e.printstacktrace ();
Response.AddHeader ("token", "Hello 2");
}finally {if (in!= null) {try {in.close ();
catch (IOException e) {}} if (out!= null) {try {out.close (); The catch (IOException e) {}}}}
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 requests/http responses, which are 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 the receiving server responds, and httpclient throws an exception if the HTTP request executes unsuccessfully. So when writing code, pay attention to finally processing.
All HTTP requests have a request line, including the method name, the URI of the request, and the HTTP version number. HttpClient supports all HTTP methods defined by this version of http/1.1: 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 ~
The above is a small series for everyone to bring the use of httpclient implementation of the file upload method of downloading all the content, I hope that we support cloud Habitat Community ~