post请求,携带json对象参数
//模拟获取token
public static String getToken() throws IOException {
//创建连接
CloseableHttpClient client = HttpClients.createDefault();
//创建http post请求
HttpPost httpPost = new HttpPost("http://39.101.66.32:"+port+"/jeecg-boot/sys/login");
//设置post参数
JsonObject j = new JsonObject();
j.addProperty("username","admin");
j.addProperty("password","Admin1234@");
//构造一个form表单式的实体
StringEntity stringEntity = new StringEntity(j.toString(),"utf-8");
//将请求实体设置到httpPost对象中
httpPost.addHeader("Content-type","application/json; charset=utf-8");
httpPost.setHeader("Accept","application/json");
httpPost.setEntity(stringEntity);
CloseableHttpResponse response = null;
try{
//执行请求
response = client.execute(httpPost);
//判断返回状态是否为200
String context = EntityUtils.toString(response.getEntity(),"utf-8");
JSONObject jsonObject = JSONObject.parseObject(context);
String token = jsonObject.getJSONObject("result").getString("token");
return token;
}finally {
if (response!=null){
response.close();
}
client.close();
}
}
PS:需注意创建 StringEntity 时,需指定编码格式utf-8,否则入参可能出现中文乱码情况
get请求,携带常规参数
//获取外置表单json
public static String getFormJson(String token,String formKey) throws IOException {
//创建连接
CloseableHttpClient client = HttpClients.createDefault();
//拼接url
StringBuilder url = new StringBuilder();
url.append("http://39.101.66.32:"+port+"/jeecg-boot/form/list?token="+token);
url.append("&isTemplate=0&pageNo=1&pageSize=1");
url.append("&code="+formKey);
//创建http get请求
HttpGet httpGet
= new HttpGet(url.toString());
CloseableHttpResponse response = null;
try {
response = client.execute(httpGet);
String context = EntityUtils.toString(response.getEntity(),"utf-8");
JSONObject jsonObject = JSONObject.parseObject(context);
String s = jsonObject.getJSONObject("result").getJSONArray("records").getJSONObject(0).getJSONObject("json").toJSONString();
return s;
}catch (Exception e){
throw new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, WorkflowMessageConstant.WORK_FLOW_DEPLOY_FAIL_FORM);
}
finally {
if(response!=null){
response.close();
}
client.close();
}
}