java代码发送https请求
1
2
3
4
5
<dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.8</version>
        </dependency>

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
public ResultVO<UserInfoDTO> test(String code, HttpSession session) {
        ResultVO<UserInfoDTO> vo = new ResultVO<>();
        if(org.apache.commons.lang3.StringUtils.isBlank(authServerUrl)){
            LOG.info("---------authServerUrl is null...");
            vo.setData(getTestToken(code, session));
            vo.setSuccess(true);
            return vo;
        }
        String codeBody = "grant_type=authorization_code"
                + "&code=" + code
                + "&redirect_uri=" + URLUtil.encode(redirectUri);
 
        try {
            HttpResponse tokenResponse = HttpUtil.createPost(authServerUrl + "/oauth2/token")
                    .contentType("application/x-www-form-urlencoded")
                    .body(codeBody)
                    .header("Authorization", "Basic " + Base64.encode(clientId + ":" + secretKey))
                    .execute();
            if (200 == tokenResponse.getStatus()) {
                String body = tokenResponse.body();
                Map<String, Object> tokenMap = JSONUtil.toBean(body, Map.class);
                String accessToken  = Convert.toStr(tokenMap.get("access_token"));
                String idToken = Convert.toStr(tokenMap.get("id_token"));
                if (accessToken != null) {
                    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(java.util.Base64.getDecoder().decode(publicKey));
                    PublicKey rsaPublicKey = SecureUtil.generatePublicKey("RSA", keySpec);
                    JWTSigner jwtSigner = JWTSignerUtil.rs256(rsaPublicKey);
                    // 使用公钥验证access_token和id_token
                    if (JWTUtil.verify(accessToken, jwtSigner) && JWTUtil.verify(idToken, jwtSigner)) {
                        // 解析JWT
                        JWT jwt = JWTUtil.parseToken(idToken);
                        String userId = (String) jwt.getPayload("id");
                        String userName = (String) jwt.getPayload("username");
                        String name = (String) jwt.getPayload("name");
                        String sid = (String) jwt.getPayload("sid");
                        LoginUser loginUser = new LoginUser();
                        loginUser.setId(userId);
                        loginUser.setUsername(userName);
                        loginUser.setName(name);
                        loginUser.setSessionId(UUIDUtils.getUUID());
                        // 将本地会话与accessToken绑定,在主动退出或调用中央4A接口时需要用到这个accessToken
                        loginUser.setAccessToken(accessToken);
                        session.setAttribute(SESSION_USER_KEY, loginUser);
                        // 绑定token中的会话ID与你的会话ID进行绑定,在被动退出登录时能够用上
                        String sessionId = session.getId();
                        // 将单点登录服务的会话ID与本地会话ID(sessionId)进行绑定,被动登出时需要用他来销毁本地会话
                        cacheManager.getCache("sid").put(sid, sessionId);
 
                        cacheManager.getCache("sessionId").put(sessionId, accessToken);
 
                        HashMap<String,Object> claims = new HashMap<String,Object>();
                        claims.put(JwtTokenUtil.ACCOUNT, loginUser.getUsername());
                        claims.put(JwtTokenUtil.NAME, loginUser.getName());
                        claims.put(JwtTokenUtil.ID, loginUser.getId());
                        claims.put(JwtTokenUtil.THIRD_ACCESS_TOKEN, loginUser.getAccessToken());
                        claims.put(JwtTokenUtil.SESSION_ID, loginUser.getSessionId());
                        String token = JwtTokenUtil.createToken(loginUser.getUsername(), claims, true);
                        UserInfoDTO dto = ModelMapperUtil.getStrictModelMapper().map(loginUser, UserInfoDTO.class);
                        dto.setToken(token);
                        vo.setSuccess(true);
                        vo.setData(dto);
                        return vo;
                    } else {
                        LOG.info("------------tokenResponse.getStatus() is " + tokenResponse.getStatus());
                        throw new TokenExpiredException("认证失败");
                    }
                }else {
                    LOG.info("------------accessToken is null...");
                    throw new TokenExpiredException("认证失败");
                }
            }else {
                LOG.info("tokenResponse.getStatus()= " + tokenResponse.getStatus());
                String body = tokenResponse.body();
                if(body != null){
                    Map<String, Object> tokenMap = JSONUtil.toBean(body, Map.class);
                    LOG.info("-------------- " + JSON.toJSONString(tokenMap));
                }
 
                throw new TokenExpiredException("认证失败");
            }
        }catch (Exception e){
            LOG.error("----------callback error...");
            LOG.info("authServerUrl: "+authServerUrl);
            LOG.info("redirectUri: "+ redirectUri);
            LOG.info("clientId: "+clientId);
            LOG.info("publicKey: " + publicKey);
            LOG.error(ExceptionUtils.getExceptionMessage(e));
            throw new TokenExpiredException("认证失败");
        }
    }

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
 
import java.io.File;
 
@Service
public class GAPlusService {
 
    private static Logger LOG = LoggerFactory.getLogger(GAPlusService.class);
 
    private static final String HEADER_PRE = "Bearer ";
 
 
    /**
     * 这个是往同一个表里面新增数据,根据传的questionId区分是哪个数据,执行成功的话,返回一个任务的id
     * @param file
     * @param access_token
     * @return
     */
    public String submitTaskAddData(File file, String access_token, String questionId){
        String headerValue = HEADER_PRE + access_token;
        String filePath = upload(file, headerValue);
        if(StringUtils.isNotBlank(filePath)){
 
            return doSubmitTaskAddData(filePath, questionId, headerValue);
        }
        return null;
    }
 
    /**
     * 调用接口上传文件,然后返回文件的路径信息
     * @param file
     * @param headerValue
     * @return
     */
    private String upload(File file, String headerValue){
        try {
            HttpResponse tokenResponse = HttpUtil.createPost(GAPlusConfig.uploadUrl)
                    .contentType("application/x-www-form-urlencoded")
                    .header("Authorization", headerValue)
                    .form("type", "zip")
                    .form("file", file)
                    .execute();
            int status = tokenResponse.getStatus();
            if (200 == status) {
                String body = tokenResponse.body();
//                Map<String, Object> tokenMap = JSONUtil.toBean(body, Map.class);
                JSONObject jsonObject = JSONUtil.parseObj(body);
                if(jsonObject.containsKey("data")){
                    return jsonObject.getStr("data");
                }else {
                    LOG.error("--------upload---------upload msg: " + jsonObject.toString());
                }
 
            }else if(401 == status){
                LOG.info("-----------upload----status is 401");
                throw new TokenExpiredException(HttpStatus.UNAUTHORIZED.value(), "登录状态已过期");
            } else {
                LOG.info("----------upload----status is " + status);
                LOG.info(tokenResponse.body());
                throw new TokenExpiredException(HttpStatus.UNAUTHORIZED.value(), "登录状态已过期");
            }
        }catch (TokenExpiredException e){
            throw new TokenExpiredException(HttpStatus.UNAUTHORIZED.value(), "登录状态已过期");
        } catch (Exception e){
            LOG.error("---------------upload error..." + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }
 
    private String doSubmitTaskAddData(String filePath, String id, String headerValue){
        try {
            HttpResponse tokenResponse = HttpUtil.createPost(GAPlusConfig.taskSubmitAddDataUrl)
                    .contentType("application/x-www-form-urlencoded")
                    .header("Authorization", headerValue)
                    .form("expression", "\"" + id + "\"")
                    .form("file_path", filePath)
                    .execute();
            int status = tokenResponse.getStatus();
            if (200 == status) {
                String body = tokenResponse.body();
//                Map<String, Object> tokenMap = JSONUtil.toBean(body, Map.class);
                JSONObject jsonObject = JSONUtil.parseObj(body);
                if(jsonObject.containsKey("data")){
                    JSONObject data = jsonObject.getJSONObject("data");
                    if(data != null && data.containsKey("id")){
                        return data.getStr("id");
                    }
                    LOG.info("-------doSubmitTaskAddData------ " + jsonObject.toString());
                }else {
                    LOG.error("-----------------doSubmitTaskAddData msg: " + jsonObject.toString());
                }
            }else {
                LOG.info("--------doSubmitTaskAddData------status is " + status);
                LOG.info(tokenResponse.body());
            }
        }catch (Exception e){
            LOG.error("---------doSubmitTaskAddData----submitTask error..." + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }
 
    public String submitTaskByGeometry(com.alibaba.fastjson.JSONObject geometry, String id, String headerValue){
        try {
            HttpResponse tokenResponse = HttpUtil.createPost(GAPlusConfig.taskSubmitByGeometryUrl)
                    .contentType("application/x-www-form-urlencoded")
                    .header("Authorization", headerValue)
                    .form("expression", "\"" + id + "\"")
                    .form("featurecollection", geometry)
                    .execute();
            int status = tokenResponse.getStatus();
            if (200 == status) {
                String body = tokenResponse.body();
//                Map<String, Object> tokenMap = JSONUtil.toBean(body, Map.class);
                JSONObject jsonObject = JSONUtil.parseObj(body);
                if(jsonObject.containsKey("data")){
                    JSONObject data = jsonObject.getJSONObject("data");
                    if(data != null && data.containsKey("id")){
                        return data.getStr("id");
                    }
                    LOG.info("-------submitTaskByGeometry------ " + jsonObject.toString());
                }else {
                    LOG.error("-----------------submitTaskByGeometry msg: " + jsonObject.toString());
                }
            }else {
                LOG.info("--------submitTaskByGeometry------status is " + status);
                LOG.info(tokenResponse.body());
                throw new TokenExpiredException(HttpStatus.UNAUTHORIZED.value(), "登录状态已过期");
            }
        }catch (TokenExpiredException e){
            throw new TokenExpiredException(HttpStatus.UNAUTHORIZED.value(), "登录状态已过期");
        } catch (Exception e){
            LOG.error("---------submitTaskByGeometry----submitTask error..." + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }
}

  

posted on   james-roger  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
历史上的今天:
2015-11-20 smartUpload组件批量下载
2015-11-20 smartUpload组件单文件下载
2015-11-20 smartUpload组件文件上传
2015-11-20 单例模式之饿汉模式与懒汉模式
点击右上角即可分享
微信分享提示