用HttpClient构造请求调用接口获取返回的JSONObject对象的步骤与方法

	@RequestMapping("/query")
    public ResBean query(@RequestBody WareBean wareBean){

        //1.请求路径
        String url = yylm_api_url+"/ware/query_ware";

        //2.创建json对象,将前端传的值存到对象中
        JSONObject jsonObject = new JSONObject();

        //3.赋值
        jsonObject.put("session_id",wareBean.getSession_id());

        //4.调用请求方法
        JSONObject json = getJSONObject(url,jsonObject);

       return null;
    }
	//封装请求对象
    public JSONObject getJSONObject(String url, JSONObject jsonObject){

        try {
            //转字符串
            String str = jsonObject.toString();
            //构造请求体
            StringEntity stringEntity = new StringEntity(str,"UTF-8");
            //构造POST请求
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(stringEntity);
            //构造请求头
            httpPost.setHeader("Content-type","application/json;charset=UTF-8");
            //创建发送https请求的httpclient
            CloseableHttpClient httpClient = HttpTooler.acceptsUntrustedCertsHttpClient();
            //执行Post请求
            CloseableHttpResponse resp = httpClient.execute(httpPost);
            //获取响应实体
            HttpEntity entity = resp.getEntity();
            //将文件中的数据读取到Java程序中
            InputStream content = entity.getContent();
            //将数据发送出去
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            int len;
            while ((len = content.read()) != -1){
                outputStream.write(len);
            }
            //可以捕获内存缓冲区的数据,转换成字节数组
            String result = new String(outputStream.toByteArray(),"utf-8");
            //将返回值转换成json格式
            JSONObject json =JSONObject.parseObject(result);
            //创建Gson对象,处理乱码
            Gson gson = new Gson();
            Collection<Object> coll = json.values();
            for (Object obj :coll){
                if (obj!=null && obj!=""){
                    if(obj.toString().indexOf("\\u") != -1){
                        //如果是unicode码则处理
                        gson.fromJson(json.getString(obj.toString()),String.class);
                    }
                }
            }
            outputStream.flush();
            outputStream.close();
            return json;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值