HttpClient-Demo

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();
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值