Http Clientを使ってインターフェースを呼び出す実例を説明します。


一、戻り先の作成

public class HttpResult {
//       
private int code;

//       
private String body;
get/set…
}
パッケージ

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;
import 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   HttpClinet,        
  this.httpClient = HttpClients.createDefault();
 }

 /**
  *     get  
  * 
  * @param url
  * @param map
  * @return
  * @throws Exception
  */
 public HttpResult doGet(String url, Map<String, Object> map) throws Exception {

  //   URIBuilder
  URIBuilder uriBuilder = new URIBuilder(url);

  //     map     
  if (map != null) {
   //     
   for (Map.Entry<String, Object> entry : map.entrySet()) {
    //     
    uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
   }
  }

  // 2   httpGet  ,     url    
  HttpGet httpGet = new HttpGet(uriBuilder.build());

  // 3   HttpClient  httpGet,      ,    
  CloseableHttpResponse response = this.httpClient.execute(httpGet);

  // 4     ,      httpResult,          
  //    
  // response.getStatusLine().getStatusCode();
  //    ,   ,  response.getEntity()  ,         ,             
  // EntityUtils.toString(response.getEntity(), "UTF-8");
  HttpResult httpResult = null;
  //       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  
  * 
  * @param url
  * @return
  * @throws Exception
  */
 public HttpResult doGet(String url) throws Exception {
  HttpResult httpResult = this.doGet(url, null);
  return httpResult;
 }

 /**
  *     post  
  * 
  * @param url
  * @param map
  * @return
  * @throws Exception
  */
 public HttpResult doPost(String url, Map<String, Object> map) throws Exception {
  //   httpPost  
  HttpPost httpPost = new HttpPost(url);

  //   map   
  if (map != null) {
   //        List  
   List<NameValuePair> params = new ArrayList<NameValuePair>();

   //   map,     list 
   for (Map.Entry<String, Object> entry : map.entrySet()) {
    params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
   }

   //   form    
   UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8");

   //         httpPost 
   httpPost.setEntity(formEntity);
  }

  //   HttpClient    ,  response
  CloseableHttpResponse response = this.httpClient.execute(httpPost);

  //   response      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  
  * 
  * @param url
  * @return
  * @throws Exception
  */
 public HttpResult doPost(String url) throws Exception {
  HttpResult httpResult = this.doPost(url, null);
  return httpResult;
 }

 /**
  *     Put  
  * 
  * @param url
  * @param map
  * @return
  * @throws Exception
  */
 public HttpResult doPut(String url, Map<String, Object> map) throws Exception {
  //   httpPost  
  HttpPut httpPut = new HttpPut(url);

  //   map   
  if (map != null) {
   //        List  
   List<NameValuePair> params = new ArrayList<NameValuePair>();

   //   map,     list 
   for (Map.Entry<String, Object> entry : map.entrySet()) {
    params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
   }

   //   form    
   UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8");

   //         httpPost 
   httpPut.setEntity(formEntity);
  }

  //   HttpClient    ,  response
  CloseableHttpResponse response = this.httpClient.execute(httpPut);

  //   response      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  
  * 
  * @param url
  * @param map
  * @return
  * @throws Exception
  */
 public HttpResult doDelete(String url, Map<String, Object> map) throws Exception {

  //   URIBuilder
  URIBuilder uriBuilder = new URIBuilder(url);

  //     map     
  if (map != null) {
   //     
   for (Map.Entry<String, Object> entry : map.entrySet()) {
    //     
    uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
   }
  }

  // 2   httpGet  ,     url    
  HttpDelete httpDelete = new HttpDelete(uriBuilder.build());

  // 3   HttpClient  httpGet,      ,    
  CloseableHttpResponse response = this.httpClient.execute(httpDelete);

  // 4     ,      httpResult,          
  //    
  // response.getStatusLine().getStatusCode();
  //    ,   ,  response.getEntity()  ,         ,             
  // EntityUtils.toString(response.getEntity(), "UTF-8");
  HttpResult httpResult = null;
  //       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;
 }

}
インターフェースを呼び出す

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();
 }

 //   
 @Test
 public void testQueryItemById() throws Exception {
  // http://manager.aaaaaa.com/rest/item/interface/{id}

  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());

 }

 //   
 @Test
 public void testSaveItem() throws Exception {
  // http://manager.aaaaaa.com/rest/item/interface/{id}

  String url = "http://manager.aaaaaa.com/rest/item/interface";

  Map<String, Object> map = new HashMap<String, Object>();
  // title=  RESTful     &price=1000&num=1&cid=888&status=1
  map.put("title", "  APIService      ");
  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());

 }

 //   

 @Test
 public void testUpdateItem() throws Exception {
  // http://manager.aaaaaa.com/rest/item/interface/{id}

  String url = "http://manager.aaaaaa.com/rest/item/interface";

  Map<String, Object> map = new HashMap<String, Object>();
  // title=  RESTful     &price=1000&num=1&cid=888&status=1
  map.put("title", "  APIService      ");
  map.put("id", "44");

  HttpResult httpResult = this.apiService.doPut(url, map);

  System.out.println(httpResult.getCode());
  System.out.println(httpResult.getBody());

 }

 //   
 @Test
 public void testDeleteItemById() throws Exception {
  // http://manager.aaaaaa.com/rest/item/interface/{id}

  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());

 }

}
以上のHttpClientを使ってインタフェースを呼び出す実例解説は小編集が皆さんに提供した内容の全部です。参考にしていただければと思います。よろしくお願いします。