增加httpClien公共类

This commit is contained in:
zhangwei
2018-05-21 09:46:49 +08:00
parent 425e76bbc1
commit fb67b37193
26 changed files with 856 additions and 3 deletions

View File

@@ -0,0 +1,179 @@
package com.nis.util;
import java.io.File;
import java.util.Map;
import javax.ws.rs.client.Invocation.Builder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;
import com.nis.util.httpclient.ClientUtil;
public class ConfigServiceUtil {
/**
* 从后台服务获取compileid,groupid,regionid
* @param type 1是compileid,2是groupid,3是regionid
* @return
*/
public static String getId(int type,int num) throws Exception {
String result = null;
String url = "";
if (type == 1) {
url = Constants.SERVICE_URL+Constants.CONFIG_ID_SOURCES+"?sourceName=CONFIG_COMPILE&num="+num;
} else if (type == 2) {
url = Constants.SERVICE_URL+Constants.CONFIG_ID_SOURCES+"?sourceName=CONFIG_GROUP&num="+num;
} else if (type == 3) {
url = Constants.SERVICE_URL+Constants.CONFIG_ID_SOURCES+"?sourceName=CONFIG_REGION&num="+num;
}
//创建连接
WebTarget wt = ClientUtil.getWebTarger(url);
//获取响应结果
Builder header = wt.request(MediaType.APPLICATION_JSON).header("Content-Type", MediaType.APPLICATION_JSON);
Response response= header.get();
if( response.getStatus() == 200){
result= response.readEntity(String.class);
}
if(result == null){
return "0";
}else{
return result;
}
}
/**
* MAAT配置提交
* @param params
* @return
* @throws Exception
*/
public static String postMaatCfg(String params) throws Exception{
String result = null;
String url = Constants.SERVICE_URL+Constants.MAAT_CFG;
//创建连接
WebTarget wt = ClientUtil.getWebTarger(url);
//获取响应结果
Builder header = wt.request(MediaType.APPLICATION_JSON).header("Content-Type", MediaType.APPLICATION_JSON);
Response response= header.get();
if( response.getStatus() == 200){
result= response.readEntity(String.class);
}else{
}
return result;
}
/**
* 回调配置提交
* @param params
* @return
* @throws Exception
*/
public static String postCallbackCfg(String params) throws Exception{
String result = null;
String url = Constants.SERVICE_URL+Constants.CALLBACK_CFG;
//创建连接
WebTarget wt = ClientUtil.getWebTarger(url);
//获取响应结果
Builder header = wt.request(MediaType.APPLICATION_JSON).header("Content-Type", MediaType.APPLICATION_JSON);
Response response= header.get();
if( response.getStatus() == 200){
result= response.readEntity(String.class);
}else{
}
return result;
}
/**
* 文件配置提交
* @param params
* @return
* @throws Exception
*/
public static String postFileCfg(String params,File file,Map<String, Object> fileDesc) throws Exception{
String result = null;
String url = Constants.SERVICE_URL+Constants.FILE_UPLOAD_CFG;
//创建连接
WebTarget wt = ClientUtil.getWebTarger(url);
FormDataMultiPart formDataMultiPart=new FormDataMultiPart();
FileDataBodyPart bodyPart=new FileDataBodyPart("file",file);
formDataMultiPart.bodyPart(bodyPart);
Builder header = wt.request(MediaType.APPLICATION_JSON).header("File-Desc",ClientUtil.formatFileDesc(fileDesc) );
Response response= header.post(Entity.entity(formDataMultiPart, formDataMultiPart.getMediaType()));
if( response.getStatus() == 200){
result= response.readEntity(String.class);
}else{
}
return result;
}
/**
* 配置删除
* @param params
* @return
*/
public static String delete(String params){
String result = "";
return result;
}
/**
* 配置文件上传
* @param params
* @return
*/
public static String put(String params){
String result = "";
return result;
}
/**
* 信息获取
* @param params
* @return
* @throws Exception
*/
public static String getFileDigest(String params,File file,Map<String, Object> fileDesc) throws Exception{
String result = null;
String url = Constants.SERVICE_URL+Constants.FILE_DIGEST_CFG;
//创建连接
WebTarget wt = ClientUtil.getWebTarger(url);
FormDataMultiPart formDataMultiPart=new FormDataMultiPart();
FileDataBodyPart bodyPart=new FileDataBodyPart("file",file);
formDataMultiPart.bodyPart(bodyPart);
Builder header = wt.request(MediaType.APPLICATION_JSON).header("File-Desc",ClientUtil.formatFileDesc(fileDesc) );
Response response= header.post(Entity.entity(formDataMultiPart, formDataMultiPart.getMediaType()));
if( response.getStatus() == 200){
result= response.readEntity(String.class);
}else{
}
return result;
}
public static void main(String[] args) {
try {
//创建连接
WebTarget wt = ClientUtil.getWebTarger("http://10.0.6.30:8080/maatRest/service/cfg/v1/getCompileId?sourceName=CONFIG_COMPILE&num=1");
//获取响应结果
Builder header = wt.request(MediaType.APPLICATION_JSON).header("Content-Type", MediaType.APPLICATION_JSON);
Response response= header.get();
if( response.getStatus() == 200){
String result= response.readEntity(String.class);
}else{
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@@ -1,6 +1,8 @@
package com.nis.util;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.GsonBuilder;
@@ -274,5 +276,11 @@ public final class Constants {
public static final String CALLBACK_CFG = Configurations.getStringProperty("callbackCfg","commonSources");
public static final String FILE_UPLOAD_CFG = Configurations.getStringProperty("fileUploadCfg","fileUploadSources");
public static final String FILE_DIGEST_CFG=Configurations.getStringProperty("fileDigestCfg","fileDigestSources");
public static final String CONFIG_ID_SOURCES=Configurations.getStringProperty("configIdSources","configPzIdSources");
/**请求头参数*/
public static final Map<String,Object> REQUEST_HEADER = new HashMap<String,Object>();
public static final Integer CLIENT_CONNECT_TIMEOUT = Configurations.getIntProperty("client_connect_timeout",1000);
public static final Integer CLIENT_READ_TIMEOUT = Configurations.getIntProperty("client_read_timeout",1000);
public static final Integer CLIENT_SOCKET_TIMEOUT = Configurations.getIntProperty("client_socket_timeout",1000);
}

View File

@@ -0,0 +1,27 @@
package com.nis.util.httpclient;
import java.io.IOException;
import java.util.Map;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.core.MultivaluedMap;
import com.nis.util.Constants;
/**
* 请求过滤器每次请求时自动配置requestHeader信息
*/
public class ClientRequestHeaderFilter implements ClientRequestFilter{
@Override
public void filter(ClientRequestContext context) throws IOException {
MultivaluedMap<String,Object> header = context.getHeaders();
Map<String,Object> h = Constants.REQUEST_HEADER;//请求头参数
if(h != null && h.size() > 0){
for(Map.Entry<String, Object> temp : h.entrySet()){
header.add(temp.getKey(), temp.getValue());
}
}
}
}

View File

@@ -0,0 +1,113 @@
package com.nis.util.httpclient;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.client.Invocation.Builder;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.apache.log4j.Logger;
import org.glassfish.jersey.client.ClientProperties;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import com.nis.util.Constants;
public class ClientUtil {
private static Client client;//客户端
private static Logger logger = Logger.getLogger(ClientUtil.class);
/**
* 初始化https client
* @throws Exception
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static void initClient(){
try{
client = ClientBuilder.newBuilder().register(ClientRequestHeaderFilter.class)//请求过滤器自动添加header信息
.register(JacksonFeature.class)//json支持
.register(MultiPartFeature.class)//文件上传支持
.property(ClientProperties.CONNECT_TIMEOUT, Constants.CLIENT_CONNECT_TIMEOUT)//连接超时时间
.property(ClientProperties.READ_TIMEOUT, Constants.CLIENT_READ_TIMEOUT)//读取超时时间
.build();
logger.info("客户端初始化成功");
}catch (Exception e) {
logger.error("初始化客户端失败,请检查证书是否正确!",e);
System.exit(1);//程序退出
}
}
/**
*path 以https://或http:// 开始不做处理否则在path前加上 Constants.BASE_URL + Constants.VERSION
* @param path
* @return
*/
public static WebTarget getWebTarger(String path){
initClient();
if(StringUtils.isNotBlank(path)){
path = formatHttpStr(path);//格式化url字符串
return client.target(path);
}
return null;
}
/**
* 格式化url字符串
* @param path
* @return
*/
public static String formatHttpStr(String path){
if( ! path.startsWith("https://") && ! path.startsWith("http://")){
path = Constants.SERVICE_URL + "/" + path;
}
path = path.replaceAll("/{2,}", "/");
int i = path.indexOf(":/") + 2;
String prefix = path.substring(0, i);
path =prefix +"/"+ path.substring(i);
return path;
}
public static Client getClient() {
return client;
}
public static void setClient(Client client) {
ClientUtil.client = client;
}
/**
*文件上传header增加Content-fileDesc属性
*格式Content-Filedesc:json格式的字段描述
* @param path
* @return
*/
public static JSONObject formatFileDesc(Map<String, Object> map){
Map<String,Object> newMap = new HashMap();
return JSONObject.fromObject(newMap);
}
public static void main(String[] args) throws ClientProtocolException, IOException {
String url = Constants.SERVICE_URL+Constants.CONFIG_ID_SOURCES;
//创建连接
WebTarget wt = ClientUtil.getWebTarger(url);
//获取响应结果
Builder header = wt.request(MediaType.APPLICATION_JSON).header("Content-Type", MediaType.APPLICATION_JSON);
Response response= header.get();
if( response.getStatus() == 200){
String result= response.readEntity(String.class);
System.out.println(result);
}
}
}