post请求,携带json对象参数
public static String getToken() throws IOException {CloseableHttpClient client = HttpClients.createDefault();HttpPost httpPost = new HttpPost("http://39.101.66.32:"+port+"/jeecg-boot/sys/login");JsonObject j = new JsonObject();j.addProperty("username","admin");j.addProperty("password","Admin1234@");StringEntity stringEntity = new StringEntity(j.toString(),"utf-8");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);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请求,携带常规参数
public static String getFormJson(String token,String formKey) throws IOException {CloseableHttpClient client = HttpClients.createDefault();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);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();}}