welcome to xlongwei.com

欢迎大家一起学习、交流、分享


QQ:9167702333 邮箱:admin@xlongwei.com

ServiceRequester 服务接口请求


分类 Java   关键字 分享   标签 java   web   发布 hongwei  1442300909440
注意 转载须保留原文链接,译文链接,作者译者等信息。  
服务接口请求工具:
  • post,提交数据,或上传文件
  • request,提交数据,解析结果为JSONObject、或XMLObject
  • paramsWithSecret,获得带密钥的初始数据,对应ServiceController的访问控制

/** http client util */
public class ServiceRequester {
private static int connectionRequestTimeout = NumberUtil.parseInt(GlobalConfig.getProperty("service.requester.connectionRequestTimeout"), 30000);
private static int connectionTimeout = NumberUtil.parseInt(GlobalConfig.getProperty("service.requester.connectionTimeout"), 30000);
private static int socketTimeout = NumberUtil.parseInt(GlobalConfig.getProperty("service.requester.socketTimeout"), 60000);

private static int maxConnTotal = NumberUtil.parseInt(GlobalConfig.getProperty("service.requester.maxConnTotal"), 384);
private static int maxConnPerRoute = NumberUtil.parseInt(GlobalConfig.getProperty("service.requester.maxConnPerRoute"), maxConnTotal);

private static RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(connectionRequestTimeout)
.setConnectTimeout(connectionTimeout)
.setSocketTimeout(socketTimeout)
.build();
public static CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.setMaxConnTotal(maxConnTotal)
.setMaxConnPerRoute(maxConnPerRoute)
.build();
public static Charset UTF8 = Charset.forName("utf-8");
public static ContentType textUtf8 = ContentType.create("text/plain", UTF8);

private static String secret = GlobalConfig.getProperty("service.controller.secret", "vyj2mtc5i1r4");
private static Logger logger = LoggerFactory.getLogger(ServiceRequester.class);
static {
TaskUtil.addShutdownHook(httpClient);
}

/**
* 提交key-value数据,返回json对象
*/
public static JSONObject request(String service, Map<String, String> params) {
JSONObject json = null;
String content = post(service, params);
if(content != null) {
try {
json = JSON.parseObject(content);
}catch(Exception e) {
logger.warn("fail to parse service response to json: "+content);
throw new RuntimeException(e);
}
}else {
logger.warn("fail to request service: "+service);
}

return json;
}

/**
* 提交json格式数据,返回json对象
*/
public static JSONObject request(String service, JSONObject body) {
JSONObject json = null;
String content = post(service, body.toJSONString());
if(content != null) {
try {
json = JSON.parseObject(content);
}catch(Exception e) {
logger.warn("fail to parse service response to json: "+content);
throw new RuntimeException(e);
}
}else {
logger.warn("fail to request service: "+service);
}

return json;
}

/**
* 提交xml格式数据,返回xml对象
*/
public static XMLObject request(String service, XMLObject body) {
XMLObject xml = null;
String content = post(service, body.toString());
if(content != null && content.length()>0) {
try {
//bug fix for server response text/plain instead of application/xml: "<response>...xml...</response>"
if(content.startsWith("\"")) content = content.substring(1, content.length()-1);
xml = XMLObject.fromXML(content);
}catch(Exception e) {
logger.warn("fail to parse service response to XMLObject: "+content);
throw new RuntimeException(e);
}
}else {
logger.warn("fail to request service: "+service);
}

return xml;
}

/**
* 提交数据,返回状态和内容
*/
@SuppressWarnings("unchecked")
public static String post(String service, Object body) {
HttpPost post = null;
try {
post = new HttpPost(service);
logger.info("request: "+service);
long s = System.currentTimeMillis();

if(body instanceof Map) {
Map<String, String> params = (Map<String, String>)body;
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (String name : params.keySet()) {
String value = params.get(name);
nvps.add(new BasicNameValuePair(name, value));
}
post.setEntity(new UrlEncodedFormEntity(nvps, UTF8));
logger.info("with params: "+JSON.toJSONString(params));
}else if(body instanceof String) {
post.setEntity(new StringEntity((String)body, UTF8));
logger.info("with body: "+body);
}else if(body != null){
logger.warn("unsupport body: "+body);
return null;
}

HttpResponse response = httpClient.execute(post);

int status = response.getStatusLine().getStatusCode();
String content = EntityUtils.toString(response.getEntity(), UTF8);

long e = System.currentTimeMillis();
logger.info("status: "+status+" "+(e-s)+" ms");
logger.info("content: "+content);

return content;
} catch (IOException e) {
if (post != null) post.abort();
logger.warn(e.getMessage(), e);
} catch (RuntimeException e) {
if (post != null) post.abort();
logger.warn(e.getMessage(), e);
} finally {
if (post != null) post.releaseConnection();
}

return null;
}

public static String post(String service, Map<String, String> params, String name, File file) {
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.RFC6532);
if(params!=null && params.size()>0) {
for(String param : params.keySet()) {
entityBuilder.addTextBody(param, params.get(param), textUtf8);
}
}
entityBuilder.addPart(name, new FileBody(file));

HttpEntity entity = entityBuilder.build();
HttpUriRequest request = RequestBuilder.post()
.setUri(service)
.setEntity(entity)
.build();

try {
HttpResponse response = httpClient.execute(request);
String string = EntityUtils.toString(response.getEntity(), UTF8);
logger.info(string);
return string;
}catch(Exception e) {
logger.warn("service requester upload failed: "+e.getMessage(), e);
return null;
}
}

public static Map<String, String> paramsWithSecret() {
Map<String, String> params = new HashMap<>();
params.put("secret", secret);
return params;
}
public static JSONObject jsonWithSecret() {
JSONObject json = new JSONObject();
json.put("secret", secret);
return json;
}
public static XMLObject xmlWithSecret() {
XMLObject xml = new XMLObject("request");
xml.add("secret", secret);
return xml;
}
}