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[]{};
}