java 通过rest接口API获取json数据

1.定义一个java实体类
该实体类对应json数据中需要获取的json对象

public class ParamterEntity {
	private String id;
	private String name;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

2.通过url获取json对象,并转化成java对象,返回java对象List

public class Test1 {
	//获取具体的url,解析json对象数据
	public List<ParamterEntity> getSpecificUrl(String url) {
		List<ParamterEntity> paramaters = new ArrayList<ParamterEntity>();
	    try { 
			    StringBuilder json = new StringBuilder();  
			    //连接url
		        URL urlObject = new URL(url);  
		        URLConnection uc = urlObject.openConnection();  
		        HttpURLConnection httpURLConnection = (HttpURLConnection)uc;
		        //伪造浏览器请求
		        httpURLConnection.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
		        httpURLConnection.setRequestProperty("Accept-Encoding", "gzip, deflate");
		        httpURLConnection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");
		        httpURLConnection.setRequestProperty("Connection", "keep-alive");
		        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		        httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0");	        
		        //读取该url返回的json数据
		        BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),"utf-8"));  
		        String inputLine = null;  
		        while ( (inputLine = in.readLine()) != null) {  
		            json.append(inputLine);  
		        } 
		        //关闭输入流
		        in.close();
		        //将json数据转换成java数据处理
				JSONObject jsonObjects =  JSONObject.fromObject(json.toString());//java 转json
				JSONArray jsonArray =  jsonObjects.getJSONArray("rows");//其中"rows"为该json对象中的一个数组,该数组也包含了一组对象
				//遍历该json对象数组
				for(int j=0;j<jsonArray.size();j++) {
					JSONObject jsonObject = jsonArray.getJSONObject(j);
					//json对象转换成ParamterEntity java对象,其中的属性需要一致
					ParamterEntity param = (ParamterEntity) JSONObject.toBean(jsonObject,ParamterEntity.class);
					paramaters.add(param);
				}	
			Thread.sleep(1000);
	    } catch (Exception e) {  
	        e.printStackTrace();  
	    }  
	    return paramaters;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值