获取token并get访问接口

package com.computing;

import com.alibaba.schedulerx.shade.net.sf.json.JSONObject;
import com.xx.utils.JsonUtil;
import com.xx.utils.OkhttpUtils;
import com.google.common.collect.Maps;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

/**
 * @author Annlla
 * @since 2021/3/10  10:14
 * @description:
 */
@Component
public class CnxxYun {

    /**
     * redis操作
     */
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Bean
    public String getRedisToten() {

        Map<String,Object> map = Maps.newHashMap();
        map.put("loginname","123");
        map.put("loginpass","123");
        String json =  OkhttpUtils.postJson("http://xxx.xxx.xxx.xxx/admin/login", JsonUtil.json(map));

        JSONObject jsonObject= JSONObject.fromObject(json);
        Yun yun=(Yun)JSONObject.toBean(jsonObject, Yun.class);

//        String yunToken = stringRedisTemplate.opsForValue().get("yunToken");
//        if (StringUtils.isNotBlank(yunToken)) {
//            if (Objects.nonNull(yun.getData())) {
//                stringRedisTemplate.opsForValue().set("yunToken", yun.getData(), 30 , TimeUnit.MINUTES);
//            }
//        }
        return yun.getData();
    }

    /**
     * 调用对方接口方法
     * @param path 对方或第三方提供的路径
     */
    public String  interfaceUtil(String path,String token) {
        String result = "";
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //get请求
            conn.setRequestMethod("GET");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("authorization",token);
            conn.setUseCaches(false);
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String str = "";
            while ((str = br.readLine()) != null) {
                result += str;
            }
            is.close();

            /**
             * 当 HttpURLConnection 是 "Connection: Keep-Alive" 模式,那么关闭 inputStream 后,并不会断开底层的 Socket 连接。
             * 这样的好处,是当需要连接到同一服务器地址时,可以复用该 Socket
             */
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {
        String path = null;
        try {
            //path = "http://xxx.xx.xxx.xxx/findAll?objectCode=business_information&linkName="+ URLEncoder.encode("陕西","utf-8")+"&offset=0&pageSize=10";
            path = "http://xxx.xx.xxx.xxx/findAll?&pageNo=1&pageSize=10&offset=1";
        } catch (Exception e) {
            e.printStackTrace();
        }

        CngbYun gbYun = new CngbYun();
        String redisToten = gbYun.getRedisToten();
        System.out.println(redisToten);
        String s = gbYun.interfaceUtil(path, redisToten);
        System.err.println(s);
    }
}

 

CngbYun 对象

package com.computing;

import lombok.Data;
import lombok.experimental.Accessors;

/**
 * @author Annlla
 * @since 2021/3/10  9:12
 * @description: 返回实例数据格式
 */

@Data
@Accessors(chain = true)
public class Yun {


    //接口是否调用成功 SUCCESS-成功 FAIL-失败
    private String status;

    //错误code
    private String errorCode;

    //
    private String errorTitle;

    //错误描述
    private String errorMsg;

    //返回数据内容
    private String data;

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }
}

 

APIFox是一个API管理平台,通常用于设计、文档化和测试RESTful API。当你需要从APIFox获取token并将其用于其他接口调用时,可以按照以下步骤进行封装: 1. **创建API客户端**:首先,在你的应用中设置一个APIFox的客户端,这通常涉及配置APIFox的URL、认证信息(如OAuth token)。 ```python import requests class ApiFoxClient: def __init__(self, api_url, client_id, client_secret): self.base_url = api_url self.auth = (client_id, client_secret) def get_token(self): response = requests.get(f"{self.base_url}/token", auth=self.auth) if response.status_code == 200: return response.json()["access_token"] else: raise Exception("Failed to fetch token.") # 使用示例 api_fox_client = ApiFoxClient('https://your-apifox-instance.com', 'your-client-id', 'your-client-secret') token = api_fox_client.get_token() ``` 2. **封装接口调用**:将获取到的token作为参数传递给需要访问的其他接口的函数,并在函数内部处理这个token。例如: ```python def call_protected_api(token, endpoint_url, params=None): headers = {'Authorization': f"Bearer {token}"} response = requests.get(endpoint_url, headers=headers, params=params) # ...处理响应... ``` 3. **使用封装后的函数**:现在你可以像这样使用`call_protected_api`来调用其他接口了: ```python protected_endpoint = "https://api.example.com/protected-resource" params = {"key": "value"} token = api_fox_client.get_token() response = call_protected_api(token, protected_endpoint, params)
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值