java项目从后端直接访问其他项目或网站获取所需内容

在没有学习springcloud或dubbo时,开发中在页面中调用其他项目的方法,获取其他网站的内容时经常会受到跨域的限制,而且在前端访问并不够安全,比如目标登录网站是使用其他网站登录系统的时候,返回的加密字符串从前台获取就显得不够安全。

此时就需要用到后台访问其他网站或项目的功能了。此方法类似于爬虫

此例使用的是spring-boot项目。使用后台访问时要引用必要的jar包

 
		    commons-io
		    commons-io
		    2.4
		
		
		    com.alibaba
		    fastjson
		    1.2.46
		
		
		    net.sf.json-lib
		    json-lib
		    2.4
		    jdk15
		
		
		    commons-fileupload
		    commons-fileupload
		    1.3.3
		

然后写访问其他网站的方法

/*我返回的是一个对象集合,可根据个人需求修改,返回一个对象时跟获取到的数据对象属性一定要相同,不然会报错*/
public static List getJson(){
		array= new ArrayList();
		String walletUrl = "目标网站的地址";
		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;
			}
			result = result.substring(result.indexOf("["),
					result.indexOf("]") + 1);
			JSONArray jsonArray = JSONArray.fromObject(result);
			for (int i = 0; i < jsonArray.toArray().length; i++) {
				Object o = jsonArray.get(i);
				JSONObject jsonObject2 = JSONObject.fromObject(o);
				VmAuthority vmAuthority = (VmAuthority) JSONObject
						.toBean(jsonObject2, VmAuthority.class);
				array.add(vmAuthority);
			}
			nVersion=array.get(0).getNversion();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return array;
	}

最后就是另一个返回数据的controller层。跟普通的返回json数据的方法相同

@RequestMapping("/outputAuthority")
	@ResponseBody
	public Map outputAuthority(){
		Map map=new HashMap();
		try {
			List list=bizAuthority.findListByLoginCode();
			map.put("rows",list);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return map;
	}

这样就能接收到目标数据了

此文参考:https://blog.csdn.net/srk950606/article/details/80219333

你可能感兴趣的:(java项目从后端直接访问其他项目或网站获取所需内容)