第一种 是用工具类实现的 工具类实现方式也很简单 ReturnMsg<Map<String, Object>> returnMsg = new ReturnMsg<>(0, "请求第三方 成功)"); String urlTemp="url"; String content=null; try{ URL url =new URL(urlTemp); HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestProperty("token",token); httpURLConnection.connect(); // 4 获取URL请求到的数据,并创建数据流接收 InputStream isString = httpURLConnection.getInputStream(); // 5 构建一个字符流缓冲对象,承载URL读取到的数据 BufferedReader isRead = new BufferedReader(new InputStreamReader(isString)); // 6 输出打印获取到的文件流 String str = ""; while ((str = isRead.readLine()) != null) { str = new String(str.getBytes(),"UTF-8"); //解决中文乱码问题 content=str; } returnMsg.setData(ParseDataUtil.getObjectMapper().readValue(content, new TypeReference<Map<String, Object>>() { })); // 7 关闭流 isString.close(); httpURLConnection.disconnect(); }catch (Exception e){ e.printStackTrace(); returnMsg.setCodeAndMsg(5000,"请求失败"); } return returnMsg; }
第二种 同json转list
List<Map<String, Object>> list = new ArrayList<>(); String urlTemp="url"; String content=null; try{ URL url =new URL(urlTemp); HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestProperty("token",token); httpURLConnection.connect(); // 4 获取URL请求到的数据,并创建数据流接收 InputStream isString = httpURLConnection.getInputStream(); // 5 构建一个字符流缓冲对象,承载URL读取到的数据 BufferedReader isRead = new BufferedReader(new InputStreamReader(isString)); // 6 输出打印获取到的文件流 String str = ""; while ((str = isRead.readLine()) != null) { str = new String(str.getBytes(),"UTF-8"); //解决中文乱码问题 content=str; } JSONArray jsonArray=JSONArray.fromObject("["+content+"]"); list=JSONArray.toList(jsonArray,Object.class); // 7 关闭流 isString.close(); httpURLConnection.disconnect(); }catch (Exception e){ e.printStackTrace(); } return list; }
不同接口访问的数据库结构不一样
json比较复杂
取值方式
解释
如 一个 父 > 子 两层关系
一个 父 > 子 > 孙 三层关系