热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

HttpClientDemo

post请求,携带json对象参数模拟获取tokenpublicstaticStringgetToken()throwsIOException{创建连接CloseableHttp
post请求,携带json对象参数

//模拟获取tokenpublic 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);//判断返回状态是否为200String 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请求,携带常规参数

//获取外置表单jsonpublic static String getFormJson(String token,String formKey) throws IOException {//创建连接CloseableHttpClient client = HttpClients.createDefault();//拼接urlStringBuilder 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();}}


推荐阅读
author-avatar
呸了个安6_552
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有