httpclient get与post样例与常见问题
1. get样例
public void excuteWind(String params) {
log.info("开始请求调用httpclent接口{}", params);
CloseableHttpResponse response = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建httppost
String result = "";
try {
// 参数
StringBuffer esbParams = new StringBuffer();
// 字符数据最好encoding以下;这样一来,某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)
esbParams.append("devices=" + constantConfig.esbWindDevice);
//esbParams.append("devices=" + URLEncoder.encode("&&", "utf-8"));
//esbParams.append("devices=" + URLEncoder.encode("&&", "utf-8"));
Date nowDate = new Date();
Date preDate = DateUtils.addDateMinutes(nowDate, -5);
String endTime = DateUtils.format(nowDate, "yyyy-MM-dd HH:mm:ss");
String startTime = DateUtils.format(preDate, "yyyy-MM-dd HH:mm:ss");
esbParams.append("&startTime="+startTime.replace(" ","+"));
esbParams.append("&endTime="+endTime.replace(" ","+"));
esbParams.append("&factors=PM25,PM10,CO,SO2,NO2,O3,WS,WD,TEMP,HUM,NOISE");
String reqUrl = "http://"+constantConfig.esbWindUrl + "?" + esbParams.toString();
log.info("url="+reqUrl);
HttpGet httpGet = new HttpGet(reqUrl);
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.setConnectionRequestTimeout(120000)
.build();
httpGet.setConfig(requestConfig);
httpGet.setHeader("Content-Type", "application/json;charset=utf8");
httpGet.setHeader("appkey", constantConfig.esbWindKey);
response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (response != null && statusCode == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();//获取结果实体
result = EntityUtils.toString(entity, "UTF-8");
log.info("result===" + result);
}
} catch (Exception e) {
log.info("getContent堆栈日志:" + ExceptionUtils.getStackTrace(e));
}
}
2. post样例
public void actualHandle() throws UnsupportedEncodingException {
log.info("接口调用处理器开始执行-CW");
//1. 创建htpclient连接,2min限时
CloseableHttpClient httpClient = null;
URI url = null;
CloseableHttpResponse response = null;
try {
// 配置信息
RequestConfig requestConfig = RequestConfig.custom()
// 设置连接超时时间(单位毫秒)
.setConnectTimeout(120000)
// 设置请求超时时间(单位毫秒)
.setConnectionRequestTimeout(120000)
// socket读写超时时间(单位毫秒)
.setSocketTimeout(120000)
// 设置是否允许重定向(默认为true)
.setRedirectsEnabled(true).build();
//url = new URI(EsbConstant.actualUrl + "?access-token=" + EsbConstant.ACCESS_TOKEN);
SysInitConfig sysInitConfig = EsbInitConfig.getSysInitConfig();
url = new URI(sysInitConfig.getGasUrl() + "?access-token=" + sysInitConfig.getGasToken());
httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "application/json;charset=utf8");
ActualVo actualVo = new ActualVo("实时数据表", 1, 100);
StringEntity stringEntity = new StringEntity(JSON.toJSONString(actualVo), "utf-8");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String res = EntityUtils.toString(entity);
ActualDto actualDto = JSON.parseObject(res, ActualDto.class);
log.info("接口调用获取数据成功-CW");
List<TpressureDevice> list = buildActualData(actualDto);
log.info("接口调用处理器结束-CW");
} catch (Exception e) {
log.info(MessageFormat.format("实时设备数据接口异常:{0}", "请处理!"));
log.info("错误信息::"+ e.getMessage());
log.info("接口调用堆栈日志:"+ ExceptionUtils.getStackTrace(e));
throw new RuntimeException("接口异常");
} finally {
//释放资源
try {
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
} catch (Exception e) {
log.info(MessageFormat.format("实时设备数据接口异常:{0}", "请处理!!"));
log.info("接口调用堆栈日志:"+ ExceptionUtils.getStackTrace(e));
}
log.info("执行器执行结束");
}
//4. 保存数据,加日志
}
3. 常见问题分析:
3.1 get请求日期中的空格问题
类似于url请求链中&startTime=2023-01-01 08:08:08 ,空格可用‘+’号替换
3.2 get请求特殊字符问题
类似于url请求链中包含特殊字符的&&用URLEncoder.encode(“&&”, “utf-8”),编码一下