首页 > 编程语言 >java http web getToken and login.

java http web getToken and login.

时间:2022-10-28 21:35:45浏览次数:48  
标签:http String javax return client import login getToken public

LogInHelper.java

package com.yd.dcap.integration.helper;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.yd.dcap.integration.EnvConfig;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.codec.binary.Base64;
import org.glassfish.jersey.jackson.JacksonFeature;

import javax.crypto.Cipher;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.client.*;
import javax.ws.rs.core.MediaType;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;

public class LogInHelper {
    public static String getToken(String account, String password) {
        Client client = ClientBuilder.newBuilder().hostnameVerifier((s1, s2) -> true).register(new JacksonFeature()).build();
        WebTarget webTarget = client.target(EnvConfig.base_url + "api/user/getPublicKey");
        Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
        PubKey publicKey = invocationBuilder.get(PubKey.class);

        byte[] decoded = Base64.decodeBase64(publicKey.data);
        RSAPublicKey pubKey;
        for (int i = 0; i < 3; i++) {
            try {
                pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
                Cipher cipher = Cipher.getInstance("RSA");
                cipher.init(Cipher.ENCRYPT_MODE, pubKey);
                String outStr = Base64.encodeBase64String(cipher.doFinal(password.getBytes(StandardCharsets.UTF_8)));
                LoginData loginData = new LoginData(account, outStr);
                LoginResponse loginResponse = client.target(EnvConfig.base_url + "api/login")
                        .request(MediaType.APPLICATION_JSON)
                        .post(Entity.entity(loginData, MediaType.APPLICATION_JSON), LoginResponse.class);
                return loginResponse.data.token;
            } catch (ProcessingException ex) {
                ex.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class PubKey {
        private int code;
        private String data;
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class LoginData {
        private String account;
        public String password;
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class LoginResponse {
        public int code;
        public LoginResponseData data;
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @JsonIgnoreProperties(ignoreUnknown = true)
    public static class LoginResponseData {
        public String token;
    }
}

 

PlatformClient.java

package com.yd.dcap.integration.helper;

import com.yd.dcap.integration.EnvConfig;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.ClientProperties;
import org.glassfish.jersey.jackson.JacksonFeature;

import javax.ws.rs.ProcessingException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.core.MediaType;
import java.util.HashMap;
import java.util.Map;

public class PlatformClient {
    //private Invocation.Builder builder;
    String token;

    public PlatformClient(String userName, String password) {
        token = LogInHelper.getToken(userName, password);
    }

    private Invocation.Builder getBuilder(String path) {
        ClientConfig configuration = new ClientConfig();
        configuration = configuration.property(ClientProperties.CONNECT_TIMEOUT, 30000);
        configuration = configuration.property(ClientProperties.READ_TIMEOUT, 30000);
        Client client = ClientBuilder.newBuilder().withConfig(configuration).hostnameVerifier((s1, s2) -> true).register(new JacksonFeature()).build();
        return client.target(EnvConfig.base_url).path(path)
                .request(MediaType.APPLICATION_JSON)
                .header("token", token);
    }

    public <T> T doPostRequest(String url, Object payload, Class<T> klass) {
        Invocation.Builder invoker = this.getBuilder(url);
        try {
            return invoker.post(Entity.entity(payload, MediaType.APPLICATION_JSON), klass);
        } catch (ProcessingException ex) {
            return invoker.post(Entity.entity(payload, MediaType.APPLICATION_JSON), klass);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public <T> T doPostRequest(String url, Object payload, String mtype, Class<T> klass) {
        Invocation.Builder invoker = this.getBuilder(url);
        try {
            return invoker.post(Entity.entity(payload, mtype), klass);
        } catch (ProcessingException ex) {
            return invoker.post(Entity.entity(payload, mtype), klass);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public <T> T doGetRequest(String url, Class<T> klass) {
        Invocation.Builder invoker = this.getBuilder(url);
        try {
            return invoker.get(klass);
        } catch (ProcessingException ex) {
            return invoker.get(klass);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    static Map<String, PlatformClient> clientMap = new HashMap<>();

    public static PlatformClient getClient(String userName, String password) {
        return clientMap.computeIfAbsent(userName, k -> new PlatformClient(userName, password));
    }
}

 

标签:http,String,javax,return,client,import,login,getToken,public
From: https://www.cnblogs.com/panda4671/p/16837573.html

相关文章

  • 使用CEfSharp之旅(7)CEFSharp 拦截 http 请求 websocket 内容
    废话不多说直接上代码:不清楚的加群:群:191065815privatevoidForm1_Load(objectsender,EventArgse){try{//更改设置......
  • ThreadHttpRequest
    importcom.alibaba.fastjson.JSONArray;importcom.alibaba.fastjson.JSONException;importcom.alibaba.fastjson.JSONObject;importjava.io.IOException;importj......
  • HttpUtils
    importorg.apache.commons.lang3.StringUtils;importorg.apache.http.Consts;importorg.apache.http.HttpEntity;importorg.apache.http.client.entity.UrlEncoded......
  • linux服务器,搭建socks5代理和http代理privoxy
    ssh-qTNf-D0.0.0.0:7070root@ip地址然后会提示输入密码即可,然后查看进程psaux|grepssh 看到这个,表示已经成功开启了7070端口的一个socks5的监听了,浏览器......
  • Wireshark解密HTTPS流量的两种方法
    原理我们先回顾一下SSL/TLS的整个握手过程:Clienthello:发送客户端的功能和首选项给服务器,在连接建立后,当希望重协商、或者响应服务器的重协商请求时会发送。versio......
  • 解决轻量级服务器 HttpProcessor TcpClient 跨域问题
    添加:processor.httpHeaders.Add("Access-Control-Allow-Origin:*");//(正确)processor.httpHeaders.Add("Access-Control-Allow-Method......
  • selenium模拟登录使用https协议的网址时报错的解决方法
    公司的测试地址是https协议的,使用使用默认的selenium登录时会出现安全提示的报错,导致无法模拟自动化。对此,笔者通过网上查找资料和实践,发现只需要简单的修改一下浏览器驱......
  • http大文件上传如何做断点续传
    ​ 前言文件上传是一个老生常谈的话题了,在文件相对比较小的情况下,可以直接把文件转化为字节流上传到服务器,但在文件比较大的情况下,用普通的方式进行上传,这可不是一个好......
  • Access to XMLHttpRequest at xxxx from origin xxx has been blocked by CORS poli
    错误:控制台报错; network自动发起了请求: 解决办法:找到\node_modules\sockjs-client\dist\sockjs.js 文件 然后crtl+g快捷键跳转到1603行,把他注释掉......
  • HTTP代理有什么功能
    经常上网的朋友可能听说过HTTP代理,但它的真正功能很多人并不清楚。在这里普及一下吧。在我们大部分的网络活动中,http是一种比较常见的网络协议,所以http代理也是普通人......