Use HttpClient to call the interface and httpclient to call the interface

Source: Internet
Author: User

Use HttpClient to call the interface and httpclient to call the interface

1. Write the returned object

Public class HttpResult {
// Response status code
Private int code;

// Response body
Private String body;
Get/set...
}

2. encapsulate HttpClient

Package cn. xxxxxx. httpclient; import java. util. arrayList; import java. util. list; import java. util. map; import org. apache. http. nameValuePair; import org. apache. http. client. entity. urlEncodedFormEntity; import org. apache. http. client. methods. closeableHttpResponse; import org. apache. http. client. methods. httpDelete; import org. apache. http. client. methods. httpGet; import org. apache. http. client. methods. httpPost; impor T org. apache. http. client. methods. httpPut; import org. apache. http. client. utils. URIBuilder; import org. apache. http. impl. client. closeableHttpClient; import org. apache. http. impl. client. httpClients; import org. apache. http. message. basicNameValuePair; import org. apache. http. util. entityUtils; public class APIService {private CloseableHttpClient httpClient; public APIService () {// 1 create HttpClinet, which is equivalent to opening the browser this. HttpClient = HttpClients. createDefault ();}/*** get request with parameters ** @ param url * @ param map * @ return * @ throws Exception */public HttpResult doGet (String url, map <String, Object> map) throws Exception {// declare URIBuilder uriBuilder = new URIBuilder (url); // judge whether the parameter map is not empty if (map! = Null) {// traversal parameter for (Map. entry <String, Object> entry: map. entrySet () {// set the uriBuilder parameter. setParameter (entry. getKey (), entry. getValue (). toString ();} // 2 create an httpGet object, which is equivalent to setting the url request address HttpGet httpGet = new HttpGet (uriBuilder. build (); // 3 Use HttpClient to execute httpGet, which is equivalent to pressing enter to initiate the request CloseableHttpResponse response = this.httpClient.exe cute (httpGet); // 4 parse the result and encapsulate the returned object httpResult, it is equivalent to displaying the corresponding result // status code // response. GetStatusLine (). getStatusCode (); // response body, String, if response. if getEntity () is null, the following code returns an error. Therefore, you must make a non-null judgment before parsing // EntityUtils. toString (response. getEntity (), "UTF-8"); HttpResult httpResult = null; // parse data encapsulation HttpResult if (response. getEntity ()! = Null) {httpResult = new HttpResult (response. getStatusLine (). getStatusCode (), EntityUtils. toString (response. getEntity (), "UTF-8");} else {httpResult = new HttpResult (response. getStatusLine (). getStatusCode (), "") ;}// return httpResult ;} /*** get request without parameters ** @ param url * @ return * @ throws Exception */public HttpResult doGet (String url) throws Exception {HttpResult httpResult = this. doGet (Url, null); return httpResult ;} /*** post request with parameters ** @ param url * @ param map * @ return * @ throws Exception */public HttpResult doPost (String url, Map <String, object> map) throws Exception {// declare httpPost request HttpPost httpPost = new HttpPost (url); // judge if (map! = Null) {// declare the List set for storing parameters List <NameValuePair> params = new ArrayList <NameValuePair> (); // traverse the map and set the parameters to the list for (Map. entry <String, Object> entry: map. entrySet () {params. add (new BasicNameValuePair (entry. getKey (), entry. getValue (). toString ();} // create form object UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity (params, "UTF-8"); // set the form object to httpPost. setEntity (formEntity);} // use Ht TpClient initiates a request and returns response CloseableHttpResponse response = this.httpClient.exe cute (httpPost); // parses the response encapsulation to return the object httpResult HttpResult httpResult = null; if (response. getEntity ()! = Null) {httpResult = new HttpResult (response. getStatusLine (). getStatusCode (), EntityUtils. toString (response. getEntity (), "UTF-8");} else {httpResult = new HttpResult (response. getStatusLine (). getStatusCode (), "") ;}// return httpResult ;} /*** post request without parameters ** @ param url * @ return * @ throws Exception */public HttpResult doPost (String url) throws Exception {HttpResult httpResult = this. d OPost (url, null); return httpResult ;} /*** Put request with parameters ** @ param url * @ param map * @ return * @ throws Exception */public HttpResult doPut (String url, Map <String, object> map) throws Exception {// declare the http post request HttpPut httpPut = new HttpPut (url); // judge whether the map is not empty if (map! = Null) {// declare the List set for storing parameters List <NameValuePair> params = new ArrayList <NameValuePair> (); // traverse the map and set the parameters to the list for (Map. entry <String, Object> entry: map. entrySet () {params. add (new BasicNameValuePair (entry. getKey (), entry. getValue (). toString ();} // create form object UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity (params, "UTF-8"); // set form object to httpPut in httpPost. setEntity (formEntity);} // use Htt PClient initiates a request and returns response CloseableHttpResponse response = this.httpClient.exe cute (httpPut); // parses the response encapsulation to return the object httpResult HttpResult httpResult = null; if (response. getEntity ()! = Null) {httpResult = new HttpResult (response. getStatusLine (). getStatusCode (), EntityUtils. toString (response. getEntity (), "UTF-8");} else {httpResult = new HttpResult (response. getStatusLine (). getStatusCode (), "") ;}// return httpResult ;} /*** Delete request with parameters ** @ param url * @ param map * @ return * @ throws Exception */public HttpResult doDelete (String url, Map <String, object> map) throws E Xception {// declare URIBuilder uriBuilder = new URIBuilder (url); // determine whether the parameter map is non-empty if (map! = Null) {// traversal parameter for (Map. entry <String, Object> entry: map. entrySet () {// set the uriBuilder parameter. setParameter (entry. getKey (), entry. getValue (). toString () ;}} // 2 create an httpGet object, which is equivalent to setting the url request address HttpDelete httpDelete = new HttpDelete (uriBuilder. build (); // 3 Use HttpClient to execute httpGet, which is equivalent to pressing enter to initiate a request CloseableHttpResponse response = this.httpClient.exe cute (httpDelete); // 4 parse the result and encapsulate the returned object httpResult, it is equivalent to displaying the corresponding result // status code // Response. getStatusLine (). getStatusCode (); // response body, String, if response. if getEntity () is null, the following code returns an error. Therefore, you must make a non-null judgment before parsing // EntityUtils. toString (response. getEntity (), "UTF-8"); HttpResult httpResult = null; // parse data encapsulation HttpResult if (response. getEntity ()! = Null) {httpResult = new HttpResult (response. getStatusLine (). getStatusCode (), EntityUtils. toString (response. getEntity (), "UTF-8");} else {httpResult = new HttpResult (response. getStatusLine (). getStatusCode (), "") ;}// return httpResult ;}}

 

3. Call the interface

Package cn. xxxxxx. httpclient. test; import java. util. hashMap; import java. util. map; import org. junit. before; import org. junit. test; import cn. itcast. httpclient. APIService; import cn. itcast. httpclient. httpResult; public class APIServiceTest {private APIService apiService; @ Before public void init () {this. apiService = new APIService ();} // query @ Test public void testQueryItemById () throws Exception {// response} String url = "http://manager.aaaaaa.com/rest/item/interface/42"; HttpResult httpResult = this. apiService. doGet (url); System. out. println (httpResult. getCode (); System. out. println (httpResult. getBody ();} // Add @ Test public void testSaveItem () throws Exception {// http://manager.aaaaaa.com/rest/item/interface/shareid} String url = "http://manager.aaaaaa.com/rest/item/interface"; Map <String, object> map = new HashMap <String, Object> (); // title = test RESTful APIs & price = 1000 & num = 1 & cid = 888 & status = 1 map. put ("title", "test APIService call New Interface"); map. put ("price", "1000"); map. put ("num", "1"); map. put ("cid", "666"); map. put ("status", "1"); HttpResult httpResult = this. apiService. doPost (url, map); System. out. println (httpResult. getCode (); System. out. println (httpResult. getBody ();} // modify @ Test public void testUpdateItem () throws Exception {// http://manager.aaaaaa.com/rest/item/interface/shareid} String url = "http://manager.aaaaaa.com/rest/item/interface"; Map <String, object> map = new HashMap <String, Object> (); // title = test RESTful APIs & price = 1000 & num = 1 & cid = 888 & status = 1 map. put ("title", "test APIService call modification interface"); map. put ("id", "44"); HttpResult httpResult = this. apiService. doPut (url, map); System. out. println (httpResult. getCode (); System. out. println (httpResult. getBody ();} // Delete @ Test public void testDeleteItemById () throws Exception {// http://manager.aaaaaa.com/rest/item/interface/shareid} String url = "http://manager.aaaaaa.com/rest/item/interface/44"; HttpResult httpResult = this. apiService. doDelete (url, null); System. out. println (httpResult. getCode (); System. out. println (httpResult. getBody ());}}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.