赞
踩
public final <Q, R> R getRequest(HttpExecutor httpExecutor, String uri, Class<R> clazz) {
R response = null;
List<NameValuePair> headers = new ArrayList<NameValuePair>();
headers.add(new BasicNameValuePair("Accept", "*/*"));
headers.add(new BasicNameValuePair("Accept-Encoding", "gzip, deflate"));
headers.add(new BasicNameValuePair("Accept-Language", "zh-CN,zh;q=0.8,en-us;q=0.5,en;q=0.3,*;q=0.2"));
headers.add(new BasicNameValuePair("Connection", "keep-alive"));
headers.add(new BasicNameValuePair("Cache-Control", "max-age=0"));
headers.add(new BasicNameValuePair("Pragma", "no-cache"));
headers.add(new BasicNameValuePair("User-Agent", "Mozilla/5.0"));
headers.add(new BasicNameValuePair("clientCode", clientCode));
headers.add(new BasicNameValuePair("tradeCode", tradeCode));
headers.add(new BasicNameValuePair("requestId", UUID.randomUUID().toString()));
try {
HttpExecutor.Response resp = httpExecutor.executeGet(uri, headers);
if (resp.isSuccess()) {
String result = resp.toString();
if (clazz.equals(String.class)) {
response = (R) result;
} else {
response = JSON.parseObject(result, clazz);
}
} else if (!resp.isNoError()) {
throw new ServiceException(resp.getErrorInfo(), NETWORK_ERROR);
} else {
throw new IllegalStateException(String.format("unexpected status code '%d'", resp.statusCode));
}
} catch (Exception e) {
throw wrapServiceException(e);
}
return response;
}
/**
* 组装请求数据
*
* @param httpExecutor
* @param uri
* @param requestBody
* @param token
* @return
*/
public final String getRequest(HttpExecutor httpExecutor, String uri, String requestBody, String token) {
List<NameValuePair> headers = new ArrayList<>();
headers.add(new BasicNameValuePair("Content-Type", "application/json"));
if (StringUtils.isNotEmpty(token)) {
headers.add(new BasicNameValuePair("token", token));
}
try {
log.info("CallServiceImpl.getRequest headers:{}", JSON.toJSONString(headers));
HttpExecutor.Response resp = httpExecutor.executeStringPost(uri, requestBody, null, headers);
if (resp.isSuccess()) {
return resp.toString();
} else if (!resp.isNoError()) {
throw new ServiceException(resp.getErrorInfo(), NETWORK_ERROR);
} else {
throw new IllegalStateException(String.format("unexpected status code '%d'", resp.statusCode));
}
} catch (Exception e) {
throw wrapServiceException(e);
}
}
不同的是请求体的封装方式。
(1)从前端传过来的请求参数是key=value形式的
(2)springmvc自动进行参数的绑定
(1)前端传过来的参数是字符串,以json格式呈现
(2)springmvc接收需要使用@RequestBody注解,对json字符串进行解析
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。