http请求post/get方式,带token 即相关参数封装解析

这篇博客介绍了如何在Java中使用HttpClient工具类进行HTTP请求,包括POST和GET方法,处理请求参数和响应数据。同时,文章还展示了JSONHelper公共类,用于JSON与Java对象之间的转换,如JSON到Map、List和POJO的转换。在实际示例中,详细演示了如何调用API接口,包括获取token、封装请求参数、处理响应结果,并进行了异常处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

http请求公共类

 参数封装公共类

出入参公共类

------返回参数公共类-----

 实际调用示例


 

http请求公共类

package org.framework.core.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
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.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.framework.core.common.model.json.AjaxJson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
/**  
 * @Description: HttpClient工具类  
 * @date: 2020年12月2日 上午9:16:16  
 */  
public class HttpClientUtils {

	private static final Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);
	
	private static RequestConfig requestConfig;

	/**
	 * 默认请求正文类型
	 */
	private static final String DEFAULT_CONTENTTYPE = "text/xml; charset=UTF-8";
	
	
	static{		
		requestConfig = RequestConfig.custom()
				// 设置连接超时时间(单位毫秒)
				.setConnectTimeout(5000)
				// 设置请求超时时间(单位毫秒)
				.setConnectionRequestTimeout(5000)
				// sock读写超时时间
				.setSocketTimeout(20000)
				// 设置是否允许重定向
				.setRedirectsEnabled(true).build();		
	}		
	
	public static AjaxJson sendMessagePost(String url, Object parmas, String contentType) {

		return sendMessagePost(url, parmas == null ? "" : JSON.toJSONString(parmas), contentType);
	}

	/**  
	 * @Description: post请求  
	 * @date: 2020年12月2日 上午9:16:16    
	 * @param url
	 * @param params
	 * @param contentType
	 * @return
	 */  
	public static AjaxJson sendMessagePost(String url, String params, String contentType) {
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		AjaxJson ajaxJson = new AjaxJson();
		HttpPost httpPost = new HttpPost(url);
		StringEntity entity = new StringEntity(params, Charset.forName("UTF-8"));		
		httpPost.addHeader("Accept", contentType == null ? DEFAULT_CONTENTTYPE : contentType);
		httpPost.setHeader("Content-Type", contentType == null ? DEFAULT_CONTENTTYPE : contentType);
		httpPost.setConfig(requestConfig);
		httpPost.setEntity(entity);
		// 响应模型
		CloseableHttpResponse response = null;
		String result = null;
		try {
			response = httpClient.execute(httpPost);
			HttpEntity responseEntity = response.getEntity();
			if (responseEntity != null) {
				result = EntityUtils.toString(responseEntity,"UTF-8");
			}
			ajaxJson.setMsg(result);			
		} catch (ClientProtocolException e) {
			exception(ajaxJson, e);
			e.printStackTrace();
		} catch (IOException e) {
			exception(ajaxJson, e);
			e.printStackTrace();
		} catch (Exception e) {
			exception(ajaxJson, e);
			e.printStackTrace();
		} finally {
			try {
				// 释放资源
				if (httpClient != null) {
					httpClient.close();
				}
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return ajaxJson;
	}
	
	/**  
	 * @Description: post请求  带token
	 * @date: 2021年3月19日 上午9:16:16    
	 * @param url
	 * @param params
	 * @param contentType
	 * @return
	 */  
	public static AjaxJson sendMessagePostToken(String url, String params, Map<String, String> header,String contentType) {
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		AjaxJson ajaxJson = new AjaxJson();
		HttpPost httpPost = new HttpPost(url);
		StringEntity entity = new StringEntity(params, Charset.forName("UTF-8"));		
		// header        
		for (Map.Entry<String, String> entry : header.entrySet()) {
			httpPost.addHeader(entry.getKey(), entry.getValue()); 
		}
		
		httpPost.addHeader("Accept", contentType == null ? DEFAULT_CONTENTTYPE : contentType);
		httpPost.setHeader("Content-Type", contentType == null ? DEFAULT_CONTENTTYPE : contentType);
		httpPost.setConfig(requestConfig);
		httpPost.setEntity(entity);
		// 响应模型
		CloseableHttpResponse response = null;
		String result = null;
		try {
			response = httpClient.execute(httpPost);
			HttpEntity responseEntity = response.getEntity();
			if (responseEntity != null) {
				result = EntityUtils.toString(responseEntity,"UTF-8");
			}
			ajaxJson.setMsg(result);			
		} catch (ClientProtocolException e) {
			exception(ajaxJson, e);
			e.printStackTrace();
		} catch (IOException e) {
			exception(ajaxJson, e);
			e.printStackTrace();
		} catch (Exception e) {
			exception(ajaxJson, e);
			e.printStackTrace();
		} finally {
			try {
				// 释放资源
				if (httpClient != null) {
					httpClient.close();
				}
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return ajaxJson;
	}
	
	
	/**  
	 * @Description: 模拟  get请求 
	 * @date: 2020年12月2日 上午9:16:16   
	 * @param url
	 * @param nameValuePairList
	 * @return
	 */  
	public static AjaxJson sendMessageGet(String url, List<NameValuePair> nameValuePairList) {
		AjaxJson ajaxJson = new AjaxJson();		
		CloseableHttpClient client = null;
		CloseableHttpResponse response = null;
		try {
			client = HttpClients.createDefault();
			URIBuilder uriBuilder = new URIBuilder(url);
			uriBuilder.addParameters(nameValuePairList);
			HttpGet httpGet = new HttpGet(uriBuilder.build());
			httpGet.addHeader("Content-Type", "application/json");
			response = client.execute(httpGet);			
			HttpEntity entity = response.getEntity();
			String result = EntityUtils.toString(entity, "UTF-8");
			ajaxJson.setMsg(result);				
		} catch (Exception e) {
			exception(ajaxJson, e);
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				if (client != null) {
					client.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return ajaxJson;
	}
	
	
	
	
	
	/**  
	 * @Description:  post请求,携带文件信息,模拟      mutipart/form-data提交数据 
	 * @date: 2020年12月2日 上午9:16:16    
	 * @param url
	 * @param paramsMap
	 * @param file
	 * @return
	 */  
	public static AjaxJson sendMessagePostFile(String url,Map<String,String> paramsMap,File file){
		CloseableHttpResponse response=null;
		AjaxJson ajaxJson = new AjaxJson();
		CloseableHttpClient client = HttpClients.createDefault();
		HttpPost post = new HttpPost(url);
		//解决中文乱码
		MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
		for(String key:paramsMap.keySet()){
			//传递字符串参数
			builder.addTextBody(key, paramsMap.get(key), ContentType.TEXT_PLAIN);
		}
		try {
			//传递文件流对象
			builder.addBinaryBody("taskFile", file, ContentType.MULTIPART_FORM_DATA, file.getName());
			HttpEntity multipart = builder.build();
			post.setEntity(multipart);
			response= client.execute(post);
			HttpEntity responseEntity = response.getEntity();
			String returnData = EntityUtils.toString(responseEntity, "UTF-8");
			ajaxJson.setMsg(returnData);
			ajaxJson.setObj(returnData);
		} catch (Exception e) {
			exception(ajaxJson, e);
			e.printStackTrace();
		} finally{
			try {
				if (response != null) {
					response.close();
				}
				if (client != null) {
					client.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
				
		return ajaxJson;
	}

	private static void exception(AjaxJson ajaxJson, Exception e) {
		ajaxJson.setSuccess(Boolean.FALSE);
		ajaxJson.setMsg("获取返回数据失败:"+e.getMessage());
	}
	
	
	/**  
	 * @Description: 把流转化为字符串  
	 * @date: 2020年12月2日 上午9:16:16    
	 * @param request
	 * @return
	 * @throws IOException
	 */  
	public static String changeRequest2String(HttpServletRequest  request) {
		
		InputStreamReader isReader = null;
		BufferedReader reader = null;
		StringBuilder sb = new StringBuilder();
		String paramters = null;
		try {
			isReader = new InputStreamReader(request.getInputStream(), "utf-8");
			reader = new BufferedReader(isReader);
			while ((paramters = reader.readLine()) != null) {
				sb.append(paramters);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if (null != isReader) {
					isReader.close();
				}
				if (null != reader) {
					reader.close();
				}
				
			} catch (IOException e) {
				e.printStackTrace();
				logger.warn("changeRequest2String 流转换为字符串异常信息:" );
			}
		}
		paramters = sb.toString();
		return paramters;
	}	
}

 参数封装公共类

package org.framework.core.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.BeanUtils;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * JSON和JAVA的POJO的相互转换
 * @author  wb
 * JSONHelper.java
 */
public final class JSONHelper {
	private static final Logger logger = LoggerFactory.getLogger(JSONHelper.class);

	// 将数组转换成JSON
	public static String array2json(Object object) {
		JSONArray jsonArray = JSONArray.fromObject(object);
		return jsonArray.toString();
	}

	// 将JSON转换成数组,其中valueClz为数组中存放的对象的Class
	public static Object json2Array(String json, Class valueClz) {
		JSONArray jsonArray = JSONArray.fromObject(json);
		return JSONArray.toArray(jsonArray, valueClz);
	}

	// 将Collection转换成JSON
	public static String collection2json(Object object) {
		JSONArray jsonArray = JSONArray.fromObject(object);
		return jsonArray.toString();
	}

	// 将Map转换成JSON
	public static String map2json(Object object) {
		JSONObject jsonObject = JSONObject.fromObject(object);
		return jsonObject.toString();
	}

	// 将JSON转换成Map,其中valueClz为Map中value的Class,keyArray为Map的key
	public static Map json2Map(Object[] keyArray, String json, Class valueClz) {
		JSONObject jsonObject = JSONObject.fromObject(json);
		Map classMap = new HashMap();

		for (int i = 0; i < keyArray.length; i++) {
			classMap.put(keyArray[i], valueClz);
		}

		return (Map) JSONObject.toBean(jsonObject, Map.class, classMap);
	}

	// 将POJO转换成JSON
	public static String bean2json(Object object) {
		JSONObject jsonObject = JSONObject.fromObject(object);
		return jsonObject.toString();
	}

	// 将JSON转换成POJO,其中beanClz为POJO的Class
	public static Object json2Object(String json, Class beanClz) {
		return JSONObject.toBean(JSONObject.fromObject(json), beanClz);
	}

	/**
	 * json转换为java对象
	 * 
	 * <pre>
	 * return JackJson.fromJsonToObject(this.answersJson, JackJson.class);
	 * </pre>
	 * 
	 * @param <T>
	 *            要转换的对象
	 * @param json
	 *            字符串
	 * @param valueType
	 *            对象的class
	 * @return 返回对象
	 */
	public static <T> T fromJsonToObject(String json, Class<T> valueType) {
		ObjectMapper mapper = new ObjectMapper();
		try {
			return mapper.readValue(json, valueType);
		} catch (JsonParseException e) {
			logger.error("JsonParseException: ", e);
		} catch (JsonMappingException e) {
			logger.error("JsonMappingException: ", e);
		} catch (IOException e) {
			logger.error("IOException: ", e);
		}
		return null;
	}

	// 将String转换成JSON
	public static String string2json(String key, String value) {
		JSONObject object = new JSONObject();
		object.put(key, value);
		return object.toString();
	}

	// 将JSON转换成String
	public static String json2String(String json, String key) {
		JSONObject jsonObject = JSONObject.fromObject(json);
		return jsonObject.get(key).toString();
	}

	/***
	 * 将List对象序列化为JSON文本
	 */
	public static <T> String toJSONString(List<T> list) {
		JSONArray jsonArray = JSONArray.fromObject(list);

		return jsonArray.toString();
	}

	/***
	 * 将对象序列化为JSON文本
	 * 
	 * @param object
	 * @return
	 */
	public static String toJSONString(Object object) {
		JSONArray jsonArray = JSONArray.fromObject(object);

		return jsonArray.toString();
	}

	/***
	 * 将JSON对象数组序列化为JSON文本
	 * 
	 * @param jsonArray
	 * @return
	 */
	public static String toJSONString(JSONArray jsonArray) {
		return jsonArray.toString();
	}

	/***
	 * 将JSON对象序列化为JSON文本
	 * 
	 * @param jsonObject
	 * @return
	 */
	public static String toJSONString(JSONObject jsonObject) {
		return jsonObject.toString();
	}

	/***
	 * 将对象转换为List对象
	 * 
	 * @param object
	 * @return
	 */
	public static List toArrayList(Object object) {
		List arrayList = new ArrayList();

		JSONArray jsonArray = JSONArray.fromObject(object);

		Iterator it = jsonArray.iterator();
		while (it.hasNext()) {
			JSONObject jsonObject = (JSONObject) it.next();

			Iterator keys = jsonObject.keys();
			while (keys.hasNext()) {
				Object key = keys.next();
				Object value = jsonObject.get(key);
				arrayList.add(value);
			}
		}

		return arrayList;
	}

	/* *//***
	 * 将对象转换为Collection对象
	 * 
	 * @param object
	 * @return
	 */
	/*
	 * public static Collection toCollection(Object object) { JSONArray
	 * jsonArray = JSONArray.fromObject(object);
	 * 
	 * return JSONArray.toCollection(jsonArray); }
	 */

	/***
	 * 将对象转换为JSON对象数组
	 * 
	 * @param object
	 * @return
	 */
	public static JSONArray toJSONArray(Object object) {
		return JSONArray.fromObject(object);
	}

	/***
	 * 将对象转换为JSON对象
	 * 
	 * @param object
	 * @return
	 */
	public static JSONObject toJSONObject(Object object) {
		return JSONObject.fromObject(object);
	}

	/***
	 * 将对象转换为HashMap
	 * 
	 * @param object
	 * @return
	 */
	public static HashMap toHashMap(Object object) {
		HashMap<String, Object> data = new HashMap<String, Object>();
		JSONObject jsonObject = JSONHelper.toJSONObject(object);
		Iterator it = jsonObject.keys();
		while (it.hasNext()) {
			String key = String.valueOf(it.next());
			Object value = jsonObject.get(key);
			data.put(key, value);
		}

		return data;
	}
	
	  /** 
	    * 将json格式的字符串解析成Map对象 <li> 
	    * json格式:{"name":"admin","retries":"3fff","testname":"ddd","testretries":"fffffffff"} 
	    */  
	   public static Map<String, Object> json2Map(String jsonStr)  {  
	       Map<String, Object> data = new HashMap<String, Object>();  
	       // 将json字符串转换成jsonObject  
	       JSONObject jsonObject = JSONObject.fromObject(jsonStr);  
	       Iterator it = jsonObject.keys();  
	       // 遍历jsonObject数据,添加到Map对象  
	       while (it.hasNext())  
	       {  
	           String key = String.valueOf(it.next());  
	           Object value = jsonObject.get(key);  
	           data.put(key, value);  
	       }  
	       return data;  
	   }  
	   
	   
	   /** 
	    * 将json格式的字符串解析成Map对象 <li> 
	    * json格式:{"name":"admin","retries":"3fff","testname":"ddd","testretries":"fffffffff"} 
	    */  
	   public static Map<String, List<Map<String, Object>>> json2MapList(String jsonStr)  {  
	       Map<String, List<Map<String, Object>>> data = new HashMap<String, List<Map<String, Object>>>();  
	       // 将json字符串转换成jsonObject  
	       JSONObject jsonObject = JSONObject.fromObject(jsonStr);  
	       Iterator it = jsonObject.keys();  
	       // 遍历jsonObject数据,添加到Map对象  
	       while (it.hasNext())  
	       {  
	           String key = String.valueOf(it.next());  
	           Object value = jsonObject.get(key);  
	           List<Map<String, Object>> list = toList(value);
	           data.put(key, list);  
	       }  
	       return data;  
	   }  

	/***
	 * 将对象转换为List<Map<String,Object>>
	 * 
	 * @param object
	 * @return
	 */
	// 返回非实体类型(Map<String,Object>)的List
	public static List<Map<String, Object>> toList(Object object) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		JSONArray jsonArray = JSONArray.fromObject(object);
		for (Object obj : jsonArray) {
			JSONObject jsonObject = (JSONObject) obj;
			Map<String, Object> map = new HashMap<String, Object>();
			Iterator it = jsonObject.keys();
			while (it.hasNext()) {
				String key = (String) it.next();
				Object value = jsonObject.get(key);
				map.put((String) key, value);
			}
			list.add(map);
		}
		return list;
	}
	
	// 返回非实体类型(Map<String,Object>)的List
	public static List<Map<String, Object>> toList(JSONArray jsonArray) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		for (Object obj : jsonArray) {
			JSONObject jsonObject = (JSONObject) obj;
			Map<String, Object> map = new HashMap<String, Object>();
			Iterator it = jsonObject.keys();
			while (it.hasNext()) {
				String key = (String) it.next();
				Object value = jsonObject.get(key);
				map.put((String) key, value);
			}
			list.add(map);
		}
		return list;
	}

	/***
	 * 将JSON对象数组转换为传入类型的List
	 * 
	 * @param <T>
	 * @param jsonArray
	 * @param objectClass
	 * @return
	 */
	public static <T> List<T> toList(JSONArray jsonArray, Class<T> objectClass) {
		return JSONArray.toList(jsonArray, objectClass);
	}

	/***
	 * 将对象转换为传入类型的List
	 * 
	 * @param <T>
	 * @param jsonArray
	 * @param objectClass
	 * @return
	 */
	public static <T> List<T> toList(Object object, Class<T> objectClass) {
		JSONArray jsonArray = JSONArray.fromObject(object);

		return JSONArray.toList(jsonArray, objectClass);
	}

	/***
	 * 将JSON对象转换为传入类型的对象
	 * 
	 * @param <T>
	 * @param jsonObject
	 * @param beanClass
	 * @return
	 */
	public static <T> T toBean(JSONObject jsonObject, Class<T> beanClass) {
		return (T) JSONObject.toBean(jsonObject, beanClass);
	}

	/***
	 * 将将对象转换为传入类型的对象
	 * 
	 * @param <T>
	 * @param object
	 * @param beanClass
	 * @return
	 */
	public static <T> T toBean(Object object, Class<T> beanClass) {
		JSONObject jsonObject = JSONObject.fromObject(object);

		return (T) JSONObject.toBean(jsonObject, beanClass);
	}

	/***
	 * 将JSON文本反序列化为主从关系的实体
	 * 
	 * @param <T>
	 *            泛型T 代表主实体类型
	 * @param <D>
	 *            泛型D 代表从实体类型
	 * @param jsonString
	 *            JSON文本
	 * @param mainClass
	 *            主实体类型
	 * @param detailName
	 *            从实体类在主实体类中的属性名称
	 * @param detailClass
	 *            从实体类型
	 * @return
	 */
	public static <T, D> T toBean(String jsonString, Class<T> mainClass,
			String detailName, Class<D> detailClass) {
		JSONObject jsonObject = JSONObject.fromObject(jsonString);
		JSONArray jsonArray = (JSONArray) jsonObject.get(detailName);

		T mainEntity = JSONHelper.toBean(jsonObject, mainClass);
		List<D> detailList = JSONHelper.toList(jsonArray, detailClass);

		try {
			BeanUtils.setProperty(mainEntity, detailName, detailList);
		} catch (Exception ex) {
			throw new RuntimeException("主从关系JSON反序列化实体失败!");
		}

		return mainEntity;
	}

	/***
	 * 将JSON文本反序列化为主从关系的实体
	 * 
	 * @param <T>泛型T 代表主实体类型
	 * @param <D1>泛型D1 代表从实体类型
	 * @param <D2>泛型D2 代表从实体类型
	 * @param jsonString
	 *            JSON文本
	 * @param mainClass
	 *            主实体类型
	 * @param detailName1
	 *            从实体类在主实体类中的属性
	 * @param detailClass1
	 *            从实体类型
	 * @param detailName2
	 *            从实体类在主实体类中的属性
	 * @param detailClass2
	 *            从实体类型
	 * @return
	 */
	public static <T, D1, D2> T toBean(String jsonString, Class<T> mainClass,
			String detailName1, Class<D1> detailClass1, String detailName2,
			Class<D2> detailClass2) {
		JSONObject jsonObject = JSONObject.fromObject(jsonString);
		JSONArray jsonArray1 = (JSONArray) jsonObject.get(detailName1);
		JSONArray jsonArray2 = (JSONArray) jsonObject.get(detailName2);

		T mainEntity = JSONHelper.toBean(jsonObject, mainClass);
		List<D1> detailList1 = JSONHelper.toList(jsonArray1, detailClass1);
		List<D2> detailList2 = JSONHelper.toList(jsonArray2, detailClass2);

		try {
			BeanUtils.setProperty(mainEntity, detailName1, detailList1);
			BeanUtils.setProperty(mainEntity, detailName2, detailList2);
		} catch (Exception ex) {
			throw new RuntimeException("主从关系JSON反序列化实体失败!");
		}

		return mainEntity;
	}

	/***
	 * 将JSON文本反序列化为主从关系的实体
	 * 
	 * @param <T>泛型T 代表主实体类型
	 * @param <D1>泛型D1 代表从实体类型
	 * @param <D2>泛型D2 代表从实体类型
	 * @param jsonString
	 *            JSON文本
	 * @param mainClass
	 *            主实体类型
	 * @param detailName1
	 *            从实体类在主实体类中的属性
	 * @param detailClass1
	 *            从实体类型
	 * @param detailName2
	 *            从实体类在主实体类中的属性
	 * @param detailClass2
	 *            从实体类型
	 * @param detailName3
	 *            从实体类在主实体类中的属性
	 * @param detailClass3
	 *            从实体类型
	 * @return
	 */
	public static <T, D1, D2, D3> T toBean(String jsonString,
			Class<T> mainClass, String detailName1, Class<D1> detailClass1,
			String detailName2, Class<D2> detailClass2, String detailName3,
			Class<D3> detailClass3) {
		JSONObject jsonObject = JSONObject.fromObject(jsonString);
		JSONArray jsonArray1 = (JSONArray) jsonObject.get(detailName1);
		JSONArray jsonArray2 = (JSONArray) jsonObject.get(detailName2);
		JSONArray jsonArray3 = (JSONArray) jsonObject.get(detailName3);

		T mainEntity = JSONHelper.toBean(jsonObject, mainClass);
		List<D1> detailList1 = JSONHelper.toList(jsonArray1, detailClass1);
		List<D2> detailList2 = JSONHelper.toList(jsonArray2, detailClass2);
		List<D3> detailList3 = JSONHelper.toList(jsonArray3, detailClass3);

		try {
			BeanUtils.setProperty(mainEntity, detailName1, detailList1);
			BeanUtils.setProperty(mainEntity, detailName2, detailList2);
			BeanUtils.setProperty(mainEntity, detailName3, detailList3);
		} catch (Exception ex) {
			throw new RuntimeException("主从关系JSON反序列化实体失败!");
		}

		return mainEntity;
	}

	/***
	 * 将JSON文本反序列化为主从关系的实体
	 * 
	 * @param <T>
	 *            主实体类型
	 * @param jsonString
	 *            JSON文本
	 * @param mainClass
	 *            主实体类型
	 * @param detailClass
	 *            存放了多个从实体在主实体中属性名称和类型
	 * @return
	 */
	public static <T> T toBean(String jsonString, Class<T> mainClass,
			HashMap<String, Class> detailClass) {
		JSONObject jsonObject = JSONObject.fromObject(jsonString);
		T mainEntity = JSONHelper.toBean(jsonObject, mainClass);
		for (Object key : detailClass.keySet()) {
			try {
				Class value = (Class) detailClass.get(key);
				BeanUtils.setProperty(mainEntity, key.toString(), value);
			} catch (Exception ex) {
				throw new RuntimeException("主从关系JSON反序列化实体失败!");
			}
		}
		return mainEntity;
	}
	
	public static String listtojson(String[] fields, int total, List list) throws Exception {
		Object[] values = new Object[fields.length];
		String jsonTemp = "{\"total\":" + total + ",\"rows\":[";
		for (int j = 0; j < list.size(); j++) {
			jsonTemp = jsonTemp + "{\"state\":\"closed\",";
			for (int i = 0; i < fields.length; i++) {
				String fieldName = fields[i].toString();
				values[i] = org.jeecgframework.tag.core.easyui.TagUtil.fieldNametoValues(fieldName, list.get(j));
				jsonTemp = jsonTemp + "\"" + fieldName + "\"" + ":\"" + values[i] + "\"";
				if (i != fields.length - 1) {
					jsonTemp = jsonTemp + ",";
				}
			}
			if (j != list.size() - 1) {
				jsonTemp = jsonTemp + "},";
			} else {
				jsonTemp = jsonTemp + "}";
			}
		}
		jsonTemp = jsonTemp + "]}";
		return jsonTemp;
	}

}

出入参公共类

------返回参数公共类-----

package com.api.entity;

import net.sf.json.JSONObject;
/**
 * 对应请求返回JSON字符串进行解析
 * @author wb
 * @date 2020-12-21
 */
public class ResponseResultForLes {	
	private String msg;
	private JSONObject data;
	private String success;
	private String errorCode; 
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	public JSONObject getData() {
		return data;
	}
	public void setData(JSONObject data) {
		this.data = data;
	}
	public String getSuccess() {
		return success;
	}
	public void setSuccess(String success) {
		this.success = success;
	}
	public String getErrorCode() {
		return errorCode;
	}
	public void setErrorCode(String errorCode) {
		this.errorCode = errorCode;
	}

}

实际调用示例

package com.api.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;


import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.hgtech.api.entity.InterfaceException;
import com.hgtech.api.entity.ProductExcuteAcceptLes;
import com.hgtech.api.entity.ResponseResultForLes;
import com.hgtech.api.service.BusinessCommonApiLesServiceI;
import com.hgtech.mes.entity.HgProductionExecutionEntity;
import com.hgtech.mes.entity.HgProductionOrderEntity;
import com.hgtech.mes.entity.HgProductionPlanEntity;


@Service("businessCommonApiLesService")
@Transactional
public class BusinessCommonApiLesServiceImpl extends CommonServiceImpl implements BusinessCommonApiLesServiceI {
	/**
	 * 接口调用示例
	 */
	@Override
	public void apportionExcuteLes(HgProductionExecutionEntity hgProductionExecutionEntity) throws Exception {
		boolean result = true;
		HgSysInterfaceLogEntity log = new HgSysInterfaceLogEntity();
		try {
			log.setCreateDate(new Date());
			ProductExcuteAcceptLes acceptLes = new ProductExcuteAcceptLes();			
			HgProductionOrderEntity orderEntity = super.getEntity(HgProductionOrderEntity.class, hgProductionExecutionEntity.getSourceDocumentId());
			if(orderEntity != null ) {
				HgProductionPlanEntity planEntity = super.getEntity(HgProductionPlanEntity.class, orderEntity.getSourceDocumentId());
				acceptLes.setProCode(planEntity.getProCode());
				acceptLes.setProName(planEntity.getProName());
				acceptLes.setSelStarttime(planEntity.getPlanStartTime());
				acceptLes.setSelEndtime(planEntity.getPlanEndTime());	
				
				// 获取token的路径
				String urlToken = "http://192.168.0.1/xxxx";
				// 获取token 请求参数封装
				JSONObject  request_data = new JSONObject();
				request_data.put("secret", "835d3bb0d47a9740bab0198e461776fe"); 
				String jsonToken = request_data.toJSONString();
				String contentType = "application/json;charset=utf-8";
				AjaxJson getJson = HttpClientUtils.sendMessagePost(urlToken, jsonToken, contentType);
				Map<String, Object> json2Map = JSONHelper.json2Map(getJson.getMsg());
				String token = (String) json2Map.get("data");
				org.framework.core.util.LogUtil.info("=====获取的token为:" + token);
				
				// 获取接口路径
				String url = "http://xxxxxx";
				//String jsonString = JSONHelper.collection2json(acceptLes);
				String jsonString = JSONHelper.bean2json(acceptLes);
				log.setReqData(jsonString);
				//String contentType = "application/json;charset=utf-8";
				// 封装带token的header
				Map<String,String> headerMap = new HashMap<>();
				headerMap.put("ext_token", token);
				headerMap.put("client_type", "extsystem");
				//headerMap.put("Accept", contentType);
				
				AjaxJson json = null;
				json = HttpClientUtils.sendMessagePostToken(url, jsonString, headerMap,contentType);
				if (json != null && StringUtil.isNotEmpty(json.getMsg())) {
					if(json.isSuccess()) {
						log.setResData(json.getMsg() + "--token" + token);
						ResponseResultForLes  resultForLes = JSONHelper.fromJsonToObject(json.getMsg(), ResponseResultForLes.class);
						if(resultForLes == null ) {
							log.setSuccessFlag("失败");
							log.setRemark("MES调用接口返回值格式错误");
							result = false;
						}else {
							if (StringUtil.isNotEmpty(resultForLes.getSuccess()) && resultForLes.getSuccess().equals("1")) {
								log.setSuccessFlag("成功");
								log.setRemark("MES调用接口成功");
							}else {
								log.setSuccessFlag("失败");
								log.setRemark("调用接口失败,失败码:" + resultForLes.getErrorCode());
								result = false;
							}
						}
					}else {
						log.setSuccessFlag("失败");
						log.setRemark("接口连接失败");
						result = false;
					}					
				}
			}else {
				log.setSuccessFlag("失败");
				log.setRemark("参数异常");
				result = false;				
			}
			this.save(log);
		} catch (Exception e) {
			log.setSuccessFlag("失败");
			log.setRemark("接口出现异常");
			result = false;
		}
		if(!result) {
			throw new InterfaceException(log.getRemark(),log);
		}
		
	}

}

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值