Last active
April 29, 2019 09:45
-
-
Save halegreen/b667a2066ff2b4eade4a14977ee3a427 to your computer and use it in GitHub Desktop.
封装Restful Api并调用
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.hq.modules.executor.service.impl; | |
import com.alibaba.fastjson.JSON; | |
import com.hq.common.utils.GenericSuperclassUtil; | |
import com.hq.common.utils.HttpResult; | |
import com.hq.common.utils.HttpUtils; | |
import com.shaw.common.model.RoadLink; | |
import com.shaw.common.model.TaskInfo; | |
import com.shaw.common.model.TrafficLightModel; | |
import com.shaw.common.model.TrafficStateData; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
import org.springframework.stereotype.Component; | |
import java.util.ArrayList; | |
import java.util.HashMap; | |
import java.util.List; | |
import java.util.Map; | |
@Component | |
public abstract class AbstractApiService { | |
private static Logger logger = LoggerFactory.getLogger(AbstractApiService.class); | |
protected static final String API_BASE_URL = "http://localhost:8088/api/v1/"; //api接口 | |
protected String uri; //对应接口类型uri | |
protected static final Map<String, Class> classMapping = new HashMap<>(); | |
protected static final Map<Class, String> methodMapping = new HashMap<>(); | |
static { | |
classMapping.put("task", TaskInfo.class); | |
classMapping.put("plan", TrafficLightModel.class); | |
classMapping.put("flow", TrafficStateData.class); | |
classMapping.put("link", RoadLink.class); | |
methodMapping.put(TaskInfo.class, "task"); | |
methodMapping.put(TrafficLightModel.class, "plan"); | |
methodMapping.put(TrafficStateData.class, "flow"); | |
methodMapping.put(RoadLink.class, "link"); | |
} | |
public Object get(String id) { | |
String url = API_BASE_URL + uri + "/get" + "/" + id; | |
logger.info("========== 请求api接口:{}", url); | |
Object ret = null; | |
try { | |
String result = HttpUtils.doGet(url); | |
ret = JSON.parseObject(result, classMapping.get(uri)); | |
return ret; | |
} catch (Exception e) { | |
logger.error("api获取info信息出错" + e.getMessage()); | |
e.printStackTrace(); | |
return ret; | |
} | |
} | |
public void add(Object info) { | |
String url = API_BASE_URL + uri + "/add"; | |
logger.info("========== 请求api接口:{}", url); | |
try { | |
String jonsInfo = JSON.toJSONString(info); | |
HttpResult result = HttpUtils.doPostJson(url, jonsInfo); | |
} catch (Exception e) { | |
logger.error("api添加info信息出错" + e.getMessage()); | |
e.printStackTrace(); | |
} | |
} | |
public void update(Object info, String id) { | |
String url = API_BASE_URL + uri + "/update"; | |
logger.info("========== 请求api接口:{}", url); | |
} | |
public void delete(String id) { | |
String url = API_BASE_URL + uri + "/delete"; | |
logger.info("========== 请求api接口:{}", url); | |
} | |
public Map<String, Object> getAll() { | |
String url = API_BASE_URL + uri + "/all"; | |
logger.info("========== 请求api接口:{}", url); | |
Map<String, Object> ret = new HashMap<>(); | |
try { | |
String result = HttpUtils.doGet(url); | |
Map<String, Object> tmp = JSON.parseObject(result, Map.class); | |
ret.put("totalCount", tmp.get("totalCount")); | |
String infosStr = (String) tmp.get("pageList"); | |
List<Object> retInfos = JSON.parseArray(infosStr, classMapping.get(uri)); | |
ret.put("pageList", retInfos); | |
} catch (Exception e) { | |
logger.error("api获取列表信息出错" + e.getMessage()); | |
e.printStackTrace(); | |
} | |
return ret; | |
} | |
public Map<String, Object> getPageList(int page, int pageSize) { | |
String url = API_BASE_URL + uri + "/list"; | |
logger.info("========== 请求api接口:{}", url); | |
Map<String, String> httpParam = new HashMap<>(); | |
httpParam.put("page", String.valueOf(page)); | |
httpParam.put("size", String.valueOf(pageSize)); | |
Map<String,Object> ret = new HashMap<>(); | |
try { | |
String result = HttpUtils.doGet(url, httpParam); | |
Map<String, Object> tmp = JSON.parseObject(result, Map.class); | |
ret.put("totalCount", tmp.get("totalCount")); | |
String infosStr = (String) tmp.get("pageList"); | |
List<Object> retInfos = JSON.parseArray(infosStr, classMapping.get(uri)); | |
ret.put("pageList", retInfos); | |
} catch (Exception e) { | |
logger.error("api获取列表信息出错" + e.getMessage()); | |
e.printStackTrace(); | |
} | |
return ret; | |
} | |
public Map<String, Object> getPageList(int page, int pageSize, String param) { | |
String url = API_BASE_URL + uri + "/list"; | |
logger.info("========== 请求api接口:{}", url); | |
Map<String, String> httpParam = new HashMap<>(); | |
httpParam.put("page", String.valueOf(page)); | |
httpParam.put("size", String.valueOf(pageSize)); | |
Map<String, Object> tmp = null; | |
Map<String, Object> ret = new HashMap<>(); | |
try { | |
String result = HttpUtils.doGet(url, httpParam); | |
tmp = JSON.parseObject(result, Map.class); | |
ret.put("totalCount", tmp.get("totalCount")); | |
List<Object> taskInfos = new ArrayList<>(); | |
String taskInfosStr = (String) tmp.get("pageList"); | |
List<Object> retTaskInfos = JSON.parseArray(taskInfosStr, classMapping.get(uri)); | |
for (Object task : retTaskInfos) { | |
if (this.uri.equals("task") && ((TaskInfo)task).getHandlerName().equals(param)) { | |
taskInfos.add(task); | |
} | |
} | |
ret.put("pageList", taskInfos); | |
} catch (Exception e) { | |
logger.error("api获取列表信息出错" + e.getMessage()); | |
e.printStackTrace(); | |
} | |
return ret; | |
} | |
protected void runBatchTask(List<String> taskIdList) { | |
} | |
protected Map<String, Object> search(Map<String, String> params) { | |
return null; | |
} | |
public Class<?> getEntityClass() { | |
return GenericSuperclassUtil.getActualTypeArgument(this.getClass()); | |
} | |
public String getUri() { | |
return uri; | |
} | |
public void setUri(String uri) { | |
this.uri = uri; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.hq.common.utils; | |
import org.apache.commons.lang.StringUtils; | |
import org.apache.http.NameValuePair; | |
import org.apache.http.client.ClientProtocolException; | |
import org.apache.http.client.config.RequestConfig; | |
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.utils.URIBuilder; | |
import org.apache.http.entity.ContentType; | |
import org.apache.http.entity.StringEntity; | |
import org.apache.http.impl.client.CloseableHttpClient; | |
import org.apache.http.impl.client.HttpClientBuilder; | |
import org.apache.http.message.BasicNameValuePair; | |
import org.apache.http.util.EntityUtils; | |
import java.io.IOException; | |
import java.net.URISyntaxException; | |
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.Map; | |
/** | |
* HttpClient工具类 | |
* | |
*/ | |
public class HttpUtils { | |
//设置连接参数 | |
private static RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(500) | |
.setSocketTimeout(30000) | |
.setConnectTimeout(5000) | |
.build(); | |
private static CloseableHttpClient getHttpClient(){ | |
return HttpClientBuilder.create().setMaxConnTotal(200) | |
.setMaxConnPerRoute(100) | |
.build(); | |
} | |
/** | |
* | |
* @return 响应体的内容 | |
* @throws IOException | |
* @throws ClientProtocolException | |
*/ | |
public static String doGet(String url) throws ClientProtocolException, IOException { | |
// 创建http GET请求 | |
HttpGet httpGet = new HttpGet(url); | |
httpGet.setConfig(config);//设置请求参数 | |
CloseableHttpResponse response = null; | |
CloseableHttpClient httpClient = getHttpClient(); | |
try { | |
// 执行请求 | |
response = httpClient.execute(httpGet); | |
// 判断返回状态是否为200 | |
if (response.getStatusLine().getStatusCode() == 200) { | |
String content = EntityUtils.toString(response.getEntity(), "UTF-8"); | |
// System.out.println("内容长度:"+content.length()); | |
return content; | |
} | |
} finally { | |
if (response != null) { | |
response.close(); | |
} | |
if(httpClient!=null){ | |
httpClient.close(); | |
} | |
} | |
return null; | |
} | |
/** | |
* 带有参数的get请求 | |
* @param url | |
* @return | |
* @throws URISyntaxException | |
* @throws IOException | |
* @throws ClientProtocolException | |
*/ | |
public static String doGet(String url , Map<String, String> params) throws URISyntaxException, ClientProtocolException, IOException{ | |
URIBuilder uriBuilder = new URIBuilder(url); | |
if(params != null){ | |
for(String key : params.keySet()){ | |
uriBuilder.setParameter(key, params.get(key)); | |
} | |
}//http://xxx?ss=ss | |
return doGet(uriBuilder.build().toString()); | |
} | |
/** | |
* 带有参数的post请求 | |
* @param url | |
* @param params | |
* @return | |
* @throws IOException | |
* @throws ClientProtocolException | |
*/ | |
public static HttpResult doPost(String url , Map<String, String> params) throws ClientProtocolException, IOException{ | |
// 创建http POST请求 | |
HttpPost httpPost = new HttpPost(url); | |
httpPost.setConfig(config); | |
if(params != null){ | |
// 设置2个post参数,一个是scope、一个是q | |
List<NameValuePair> parameters = new ArrayList<>(0); | |
for(String key : params.keySet()){ | |
parameters.add(new BasicNameValuePair(key, params.get(key))); | |
} | |
// 构造一个form表单式的实体 | |
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters); | |
// 将请求实体设置到httpPost对象中 | |
httpPost.setEntity(formEntity); | |
} | |
CloseableHttpResponse response = null; | |
CloseableHttpClient httpClient = getHttpClient(); | |
try { | |
// 执行请求 | |
response = httpClient.execute(httpPost); | |
// 判断返回状态是否为200 | |
/*if (response.getStatusLine().getStatusCode() == 200) { | |
String content = EntityUtils.toString(response.getEntity(), "UTF-8"); | |
System.out.println(content); | |
}*/ | |
return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(response.getEntity(), "UTF-8")); | |
} finally { | |
if (response != null) { | |
response.close(); | |
} | |
if(httpClient!=null){ | |
httpClient.close(); | |
} | |
} | |
} | |
public static HttpResult doPostJson(String url , String json) throws ClientProtocolException, IOException{ | |
// 创建http POST请求 | |
HttpPost httpPost = new HttpPost(url); | |
httpPost.setConfig(config); | |
if(StringUtils.isNotBlank(json)){ | |
//标识出传递的参数是 application/json | |
StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON); | |
httpPost.setEntity(stringEntity); | |
} | |
CloseableHttpResponse response = null; | |
CloseableHttpClient httpClient = getHttpClient(); | |
try { | |
// 执行请求 | |
response = httpClient.execute(httpPost); | |
// 判断返回状态是否为200 | |
/*if (response.getStatusLine().getStatusCode() == 200) { | |
String content = EntityUtils.toString(response.getEntity(), "UTF-8"); | |
System.out.println(content); | |
}*/ | |
return new HttpResult(response.getStatusLine().getStatusCode(),EntityUtils.toString(response.getEntity(), "UTF-8")); | |
} finally { | |
if (response != null) { | |
response.close(); | |
} | |
//httpClient.close(); | |
} | |
} | |
/** | |
* 没有参数的post请求 | |
* @throws IOException | |
* @throws ClientProtocolException | |
*/ | |
public static HttpResult doPost(String url) throws ClientProtocolException, IOException{ | |
return doPost(url, null); | |
} | |
/** | |
* 不带参数的delete | |
* | |
* @param uri | |
* @return | |
* @throws Exception | |
*/ | |
public HttpResult doDelete(String uri) throws Exception { | |
return this.doDelete(uri, null); | |
} | |
/** | |
* 带参数的delete | |
* | |
* @param url | |
* @param map | |
* @return | |
* @throws Exception | |
*/ | |
public HttpResult doDelete(String url, Map<String, Object> map) throws Exception { | |
URIBuilder uriBuilder = new URIBuilder(url); | |
if (map != null) { | |
for (Map.Entry<String, Object> entry : map.entrySet()) { | |
uriBuilder.setParameter(entry.getKey(), entry.getValue().toString()); | |
} | |
} | |
HttpDelete httpDelete = new HttpDelete(uriBuilder.build()); | |
CloseableHttpClient httpClient = getHttpClient(); | |
CloseableHttpResponse response = httpClient.execute(httpDelete); | |
int code = response.getStatusLine().getStatusCode(); | |
String body = null; | |
if (response.getEntity() != null) { | |
body = EntityUtils.toString(response.getEntity(), "UTF-8"); | |
} | |
return new HttpResult(code, body); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment