本文主要是介绍【java】从后端访问一个http地址,获得一个json串,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
@Value("${wallet.net}")private String walletNet;@Value("${wallet.contractaddress}")private String contractAddress;@Value("${wallet.urlend}")private String urlEnd;
上边是从配置文件获取一下地址。
public List<WalletUrlAmountInfo> getWalletUrlAmount(int userId)throws Exception {TBaseUser user = tBaseUserMapper.selectByPrimaryKey(userId);String walletUrl = walletNet + "&" + contractAddress + "&adrees="+ user.getCandyWalletAddress() + "&" + urlEnd;PrintWriter out = null;BufferedReader in = null;String result = "";try {URL getwalletAmountUrl = new URL(walletUrl);System.out.println(walletUrl);
//打开连接,获取返回信息。URLConnection context = getwalletAmountUrl.openConnection();in = new BufferedReader(new InputStreamReader(context.getInputStream(), "UTF-8"));String line;while ((line = in.readLine()) != null) {result += line;}System.out.println(result);result = result.substring(result.indexOf("["),result.indexOf("]") + 1);System.out.println(result);
//json与对象之间的转换
JSONArray jsonArray = JSONArray.fromObject(result);System.out.println(jsonArray);List<WalletUrlAmountInfo> array = new ArrayList<WalletUrlAmountInfo>();for (int i = 0; i < jsonArray.toArray().length; i++) {Object o = jsonArray.get(i);JSONObject jsonObject2 = JSONObject.fromObject(o);WalletUrlAmountInfo walletUrlAmountInfo = (WalletUrlAmountInfo) JSONObject.toBean(jsonObject2, WalletUrlAmountInfo.class);array.add(walletUrlAmountInfo);}return array;} catch (Exception e) {throw e;}}
json与对象转换需要的包:
这篇关于【java】从后端访问一个http地址,获得一个json串的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!