In Java background development, we sometimes need to call other Web site interface for data acquisition operations, we generally use
URL classes in the 1.java NET package for data acquisition on the network
2. Using Apache-provided httpclient for data acquisition in the network;
Here we use the second way, using the httpclient provided by Apache for data acquisition, interface docking, the following is attached to the Httpclientutil tool class, the implementation of the post and get method
PackageCom.project.util;Importjava.io.IOException;Importorg.apache.http.HttpEntity;ImportOrg.apache.http.HttpResponse;Importorg.apache.http.client.ClientProtocolException;ImportOrg.apache.http.client.methods.HttpGet;ImportOrg.apache.http.client.methods.HttpPost;Importorg.apache.http.entity.StringEntity;Importorg.apache.http.impl.client.CloseableHttpClient;Importorg.apache.http.impl.client.DefaultHttpClient;Importorg.apache.http.impl.client.HttpClients;Importorg.apache.http.util.EntityUtils; Public classHttpclientutil {//using httpclient for Doget requests Public Staticstring doget (string url) {string result=NULL; //defaulthttpclient httpclient =new defaulthttpclient ();//old version of the methodCloseablehttpclient httpclient =Httpclients.createdefault (); HttpGet HttpGet=Newhttpget (URL); Try{HttpResponse response=Httpclient.execute (HttpGet); Httpentity Entity=response.getentity (); if(Entity! =NULL) {result=entityutils.tostring (Entity, "UTF-8"); } } Catch(Exception e) {e.printstacktrace (); } finally { Try { if(HttpClient! =NULL) {httpclient.close (); } } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } } returnresult; } Public Static voidMain (string[] args) {String str=doget ("http://www.baidu.com"); System.out.println (str); } //use httpclient for DOPOSTT requests, suitable for sending data in JSON data format Public Staticstring DoPOST (String url,string outstr) {//defaulthttpclient httpclient =new defaulthttpclient ();//old version of the methodCloseablehttpclient httpclient =Httpclients.createdefault (); HttpPost HttpPost=Newhttppost (URL); String result=NULL; Try{httppost.setentity (NewStringentity (outstr, "UTF-8")); HttpResponse Response=Httpclient.execute (HttpPost); Httpentity Entity=response.getentity (); if(Entity! =NULL) {result=entityutils.tostring (Entity, "UTF-8"); } } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); } finally { Try { if(HttpClient! =NULL) {httpclient.close (); } } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } } returnresult; } }
httpclient--using HttpClient for get POST request access