java内网链接怎么让外网可用:转换成流

这篇博客介绍了如何通过Java的RestTemplate获取JSON数据,然后使用Gson库解析三层嵌套的JSON,提取出商品图片的URL。接着,将图片URL转换为Base64编码的字符串,并存入JSON对象中。整个过程涉及HTTP请求、JSON解析和图片处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.首先接收到了json格式数据
此处我是通过调用别人接口获取的数据:

	 RestTemplate restTemplate =new RestTemplate();
	 ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(orderDetailsMsg+"?orderId="+orderId,
	                HttpMethod.POST, paramEntity, JSONObject.class);
	 JSONObject resultJson = responseEntity.getBody();

2.获取到的数据格式为:
3层嵌套,因此写实体类获取具体rows值

 Gson gson = new Gson();
        MyOrderRowsVo myOrderRowsVo = gson.fromJson(resultJson.toString(), MyOrderRowsVo.class);
        JSONObject jsonOrder = myOrderRowsVo.getRows();
        MyOrderVo myOrderVo = gson.fromJson(jsonOrder.toString(), MyOrderVo.class);
        JSONObject goodsinfo = myOrderVo.getGoodsinfo();
        String picUrl = goodsinfo.getString("商品图片");
        log.info("图片url:"+picUrl);
        //图片后缀
        String fileExtName = picUrl.substring(picUrl.lastIndexOf(".") + 1,picUrl.lastIndexOf(".") + 4);
        //转换成流
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(picUrl).openConnection();
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                byte[] imageByte = inputStreamToByteArray(inputStream);//得到图片的二进制数据
                String image  = Base64Utils.encodeToString(imageByte);
                resultJson.put("picUrl", "data:image/"+fileExtName+";base64,"+image);
            }
        } catch (IOException e) {
            System.out.println("获取网络图片转换成流出现异常,图片路径为:" + picUrl);
            e.printStackTrace();
        }

        log.info("通过id{}查询我发起的单接口返回结果=={}",orderId, resultJson);

3.用到的方法:

/**
     * inputStream转byte数组
     *
     * @param inputStream 输入流对象
     * @return byte数组
     */
    public static byte[] inputStreamToByteArray(InputStream inputStream) {
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int num;
            while ((num = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, num);
            }
            byteArrayOutputStream.flush();
            return byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new byte[]{};
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值