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

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

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

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

 <dependency>
		    <groupId>commons-io</groupId>
		    <artifactId>commons-io</artifactId>
		    <version>2.4</version>
		</dependency>
		<dependency>
		    <groupId>com.alibaba</groupId>
		    <artifactId>fastjson</artifactId>
		    <version>1.2.46</version>
		</dependency>
		<dependency>
		    <groupId>net.sf.json-lib</groupId>
		    <artifactId>json-lib</artifactId>
		    <version>2.4</version>
		    <classifier>jdk15</classifier>
		</dependency>
		<dependency>
		    <groupId>commons-fileupload</groupId>
		    <artifactId>commons-fileupload</artifactId>
		    <version>1.3.3</version>
		</dependency>

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

/*我返回的是一个对象集合,可根据个人需求修改,返回一个对象时跟获取到的数据对象属性一定要相同,不然会报错*/
public static List<VmAuthority> getJson(){
		array= new ArrayList<VmAuthority>();
		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<String, Object> outputAuthority(){
		Map<String,Object> map=new HashMap<String, Object>();
		try {
			List<DmAuthorize> 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

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值