最开始的代码如下,:
@Controller
@RequestMapping("lock")
@Api(value = "车锁信息", description = "车锁信息管理")
public class LockController {
@SuppressWarnings("unchecked")
@RequestMapping(value = "findInformation", method = RequestMethod.POST)
@ApiOperation("查询车锁秘钥")
@ResponseBody
public Result<?> findInformation(String parentTaskNo) {
Result<String> result = new Result<>();
// TODO Auto-generated method stub
HttpClient client = new DefaultHttpClient();
String path = "http://10.118.61.66:8888/services/lock/getLockKeyByNo";
HttpGet get = new HttpGet(path);
get.setHeader("lockNo", parentTaskNo);
HttpResponse response = null;
try {
response = client.execute(get);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
StatusLine status = response.getStatusLine();
int statusCode = status.getStatusCode();
System.out.println(statusCode);
if (statusCode == HttpStatus.SC_OK) {// 响应码200
HttpEntity entity = response.getEntity();
Gson gson = new Gson();
try {
String string = EntityUtils.toString(entity, "utf-8");
System.out.println("entity" + string);
// Student stu = gson.fromJson(json, Student.class);
result = gson.fromJson(string, Result.class);
System.out.println("result: " + result.toString());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
第一次封装后如下,用post方法接收数据,请求用对象接收,把请求用map接收,并写出请求工具类:
String path = ConstantUtil.GOAL_URL + ConstantUtil.GOAL_PORT + ConstantUtil.UPDATE_UNLOAD_TASK_STATUS;
String taskNo= request.getTaskNo();
String taskStatus = request.getTaskStatus();
String transitDepotNo = request.getTransitDepotNo();
Map<String, String> params = new HashMap<>();
params.put("taskNo", taskNo);
params.put("taskStatus", taskStatus);
params.put("transitDepotNo", transitDepotNo);
Result<String> result = HttpUtils.putByHeader(path, params, Result.class);
return result;
工具类:
/**
* get请求,参数封装到请求头中
*
* @param url 请求url
* @param params 请求参数
* @return String json字符串
*/
public static String getByHeader(String url, Map<String, String> params) {
@SuppressWarnings("resource")
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = null;
String res = null;
try {
//设置请求头信息
if(null != params && !params.isEmpty()) {
for (Map.Entry<String, String> entrySet : params.entrySet()) {
httpGet.setHeader(entrySet.getKey(), entrySet.getValue());
}
}
response = httpClient.execute(httpGet);
StatusLine status = response.getStatusLine();
Integer statusCode = status.getStatusCode();
System.out.println(statusCode);
if (statusCode == HttpStatus.SC_OK) {// 响应码200
HttpEntity entity = response.getEntity();
res = EntityUtils.toString(entity, "utf-8");
System.out.println("entity" + res);
return res;
}
return res;
} catch (Exception e) {
e.printStackTrace();
return res;
} finally {
httpGet.releaseConnection();
}
}
第二次优化,利用反射,直接将对象转为map:
Map<String, String> params = ObjToMap.obj2Map(requst);
System.out.println(params);
Result<List<LoadCarTaskListResponse>> result = HttpUtils.getByHeader(path, params,Result.class);
return result;
转对象为map的工具类:
public class ObjToMap {
public static Map<String, String> obj2Map(Object obj) {
Map<String, String> map = new HashMap<String, String>();
// System.out.println(obj.getClass());
// 获取f对象对应类中的所有属性域
Field[] fields = obj.getClass().getDeclaredFields();
for (int i = 0, len = fields.length; i < len; i++) {
String varName = fields[i].getName();
varName = varName.toLowerCase();//将key置为小写,默认为对象的属性
try {
// 获取原来的访问控制权限
boolean accessFlag = fields[i].isAccessible();
// 修改访问控制权限
fields[i].setAccessible(true);
// 获取在对象f中属性fields[i]对应的对象中的变量
Object o = fields[i].get(obj);
if (o != null)
map.put(varName, o.toString());
// System.out.println("传入的对象中包含一个如下的变量:" + varName + " = " + o);
// 恢复访问控制权限
fields[i].setAccessible(accessFlag);
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
}
}
return map;
}
}
第三次优化,将两个工具类和在一次
Result<List<LoadCarTaskListResponse>> result = HttpUtils.getByHeader(path, obj,Result.class);```
第四次,使用Jersey,指明路径,请求体,结果体,以及描述路径即可,使用TYPE
解决对象解析问题
import java.lang.reflect.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.sf.framework.domain.Result;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
/**
*
* @author 80002834 on 2017/10/26 17:32
* @Description: 调用微服务restful接口
*
*/
public class HttpUtils {
private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);
private static final Client CLIENT = Client.create();
private static final Gson GSON = new Gson();
private static final String ACCEPT = ": accept: ";
private static final String PATH = "path= ";
private static final String APPJSON = "application/json";
private static final String RESPONSE = ": response: ";
/**
*
* @param path
* @param request
* @param result
* @param describe
* @return
*/
@SuppressWarnings("serial")
public static <T> Result<T> post(String path, Object request, Result<T> result, String describe) {
if (request != null) {
logger.info("\n" + describe + ACCEPT + request + "\n" + PATH + path);
WebResource webResource = CLIENT.resource(path);
String response = webResource.accept(APPJSON).type(APPJSON).post(String.class,
new Gson().toJson(request));
logger.info("\n" + describe + RESPONSE + response);
result = GSON.fromJson(response, new TypeToken<Result<T>>() {}.getType());
} else {
result.setSuccess(false);
}
return result;
}
/**
*
* @param path
* @param request
* @param result
* @param describe
* @return Result
*/
@SuppressWarnings({ "serial" })
public static <T> Result<T> put(String path, Object request, Result<T> result, String describe) {
logger.info("\n" + describe + ACCEPT + request + "\n" + PATH + path);
WebResource webResource = CLIENT.resource(path);
String response = webResource.accept(APPJSON).type(APPJSON).put(String.class,
new Gson().toJson(request));
logger.info("\n" + describe + RESPONSE + response);
result = GSON.fromJson(response, new TypeToken<Result<T>>() {}.getType());
return result;
}
/**
*
* @param path
* @param result
* @param describe
* @return Result
*/
@SuppressWarnings("serial")
public static <T> Result<T> get(String path, Result<T> result, String describe) {
logger.info("\n" + describe + "\n" + PATH + path);
WebResource webResource = CLIENT.resource(path);
String response = webResource.accept(APPJSON).type(APPJSON).get(String.class);
logger.info("\n" + describe + RESPONSE + response);
result = GSON.fromJson(response, new TypeToken<Result<T>>() {}.getType());
return result;
}
“`
gson解析问题:https://www.cnblogs.com/qq78292959/p/3781808.html