返回结果实体类
public class HttpResult {
private Integer code;
private String body;
public HttpResult() {
super();
}
public HttpResult(Integer code, String body) {
super();
this.code = code;
this.body = body;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}
POST请求接口
public HttpResult doPost(String url, String requestParam) throws Exception {
HttpPost httpPost = new HttpPost(url);
config = RequestConfig.custom().setSocketTimeout(6000).setConnectTimeout(6000).build();
httpPost.setConfig(config);
httpPost.setHeader("key", "value");
if (null != requestParam) {
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept", "application/json");
httpPost.setEntity(new StringEntity(requestParam, Charset.forName("UTF-8")));
}
CloseableHttpResponse response = this.httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
String entity = EntityUtils.toString(
response.getEntity(), "UTF-8");
HttpResult httpResult = new HttpResult(statusCode, entity);
return httpResult;
}
调用发送doPost方法
try {
JSONObject postJson = new JSONObject();
postJson.put("imei", dto.getImei());
HttpResult httpResult = 类名.doPost(url,postJson.toString());
JSONObject job = JSONObject.parseObject(httpResult.getBody());
JSONObject obj = (JSONObject)job.get("data");
smokeDetectorLogDO.setSiteId(String.valueOf(obj.get("siteId")));
smokeDetectorLogDO.setSiteName((String)obj.get("siteName"));
smokeDetectorLogDO.setBatteryLevel(String.valueOf(obj.get("batteryLevel")));
smokeDetectorLogDO.setId(UUID.randomUUID().toString());
}catch (ServiceException e) {
throw new ServiceException(e.getCode(),e.getMsg());
}catch (Exception e) {
System.out.println("查询数据时系统出现异常!");
e.printStackTrace();
}