首页 > 其他分享 >请求需要登录的接口

请求需要登录的接口

时间:2023-03-29 21:44:07浏览次数:33  
标签:return String 登录 http 接口 str import public 请求

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.75</version>
        </dependency>

        <dependency>
            <groupId>com.antherd</groupId>
            <artifactId>sm-crypto</artifactId>
            <version>0.3.2</version>
        </dependency>

        <!--hutool-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.5.8</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.3.2.RELEASE</version>
        </dependency>

        <!--http客户端-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.13</version>
        </dependency>



        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.0.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>2.3.2.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>22.0</version>
        </dependency>


        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-http</artifactId>
            <version>5.5.1</version>
        </dependency>

keypair类

/**
 * 基于SM2的秘钥对
 * (本项目中配置的,自己使用可根据自己的需求进行更换)
 */
public class keypair {

    /**
     * 公钥
     */
    public static String PUBLIC_KEY = "04298364ec840088475eae92a591e01284d1abefcda348b47eb324bb521bb03b0b2a5bc393f6b71dabb8f15c99a0050818b56b23f31743b93df9cf8948f15ddb54";

    /**
     * 私钥
     */
    public static String PRIVATE_KEY = "3037723d47292171677ec8bd7dc9af696c7472bc5f251b2cec07e65fdef22e25";

    /**
     * SM4的对称秘钥(生产环境需要改成自己使用的)
     * 16 进制字符串,要求为 128 比特
     */
    public static String KEY = "0123456789abcdeffedcba9876543210";

}

CryptogramUtill类

import cn.hutool.log.Log;
import com.antherd.smcrypto.sm2.Sm2;
import com.antherd.smcrypto.sm3.Sm3;
import com.antherd.smcrypto.sm4.Sm4;
import com.antherd.smcrypto.sm4.Sm4Options;

/**
 * 加密工具类,本框架目前使用 https://github.com/antherd/sm-crypto 项目中一些加解密方式
 * 使用小伙伴需要过等保密评相关,请在此处更改为自己的加密方法,或加密机,使用加密机同时需要替换公钥,私钥在内部无法导出,提供加密的方法
 */
public class CryptogramUtil {

    private static final Log log = Log.get();

    /**
     * 加密方法(Sm2 的专门针对前后端分离,非对称秘钥对的方式,暴露出去的公钥,对传输过程中的密码加个密)
     *
     * @param str 待加密数据
     * @return 加密后的密文
     */
    public static String doSm2Encrypt (String str) {
        return Sm2.doEncrypt(str, keypair.PUBLIC_KEY);
    }

    /**
     * 解密方法
     * 如果采用加密机的方法,用try catch 捕捉异常,返回原文值即可
     * @param str 密文
     * @return 解密后的明文
     */
    public static String doSm2Decrypt (String str) {
        // 解密
        return Sm2.doDecrypt(str, keypair.PRIVATE_KEY);
    }

    /**
     * 加密方法
     * @param str 待加密数据
     * @return 加密后的密文
     */
    public static String doEncrypt (String str) {
        // SM4 加密  cbc模式
        Sm4Options sm4Options4 = new Sm4Options();
        sm4Options4.setMode("cbc");
        sm4Options4.setIv("fedcba98765432100123456789abcdef");
        return Sm4.encrypt(str, keypair.KEY, sm4Options4);
    }

    /**
     * 解密方法
     * 如果采用加密机的方法,用try catch 捕捉异常,返回原文值即可
     * @param str 密文
     * @return 解密后的明文
     */
    public static String doDecrypt (String str) {
        // 解密,cbc 模式,输出 utf8 字符串
        Sm4Options sm4Options8 = new Sm4Options();
        sm4Options8.setMode("cbc");
        sm4Options8.setIv("fedcba98765432100123456789abcdef");
        String docString =  Sm4.decrypt(str, keypair.KEY, sm4Options8);
        if (docString.equals("")) {
            log.warn(">>> 字段解密失败,返回原文值:{}", str);
            return str;
        } else {
            return docString;
        }
    }

    /**
     * 纯签名
     * @param str 待签名数据
     * @return 签名结果
     */
    public static String doSignature (String str) {
        return Sm2.doSignature(str, keypair.PRIVATE_KEY);
    }

    /**
     * 验证签名结果
     * @param originalStr 签名原文数据
     * @param str 签名结果
     * @return 是否通过
     */
    public static boolean doVerifySignature (String originalStr, String str) {
        return Sm2.doVerifySignature(originalStr, str, keypair.PUBLIC_KEY);
    }

    /**
     * 通过杂凑算法取得hash值,用于做数据完整性保护
     * @param str 字符串
     * @return hash 值
     */
    public static String doHashValue (String str) {
        return Sm3.sm3(str);
    }

}

HttpRequestUtil类

import com.alibaba.fastjson.JSON;
import net.minidev.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 */
public class HttpRequestUtil {

    private String DATA_ENCODING = "DataEncoding";
    private String CONTENT_TYPE = "Content-Type";
    private String APPLICATION_JSON = "application/json";
    public CloseableHttpClient httpClient;
    public HttpServletRequest request;

    public HttpRequestUtil() {
    }

    /**
     * 免登录请使用该构造方法创建httpClient对象,
     * 调用系统中的接口,不需要再次使用账户密码进行登录,不支持第三方接口
     *
     * @param hostIP  这个参数特别重要,为了给请求设置domain,具体看下面第3小点
     * @param request 当次前端发起的请求
     */
    public HttpRequestUtil(HttpServletRequest request, String hostIP) {
        //设置http的cookie,把前端请求的sessionID加入到httpUtil中
        BasicCookieStore cookieStore = new BasicCookieStore();
        BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", request.getSession().getId());
        //设置cookie的domain信息,否则sessionID无法生效
        //String ipAddr = IpUtils.getIpAddr(request);
        cookie.setDomain(hostIP);
        /**
         * 设置cookie的Path信息,为全局的url,如:如http://shuizhu.com/api/xxx/xxx,该path就是"/api"
         * 如果没有该path,下面的代码最好写上
         */
        cookie.setPath(request.getContextPath());
        cookieStore.addCookie(cookie);
        this.request = request;
        //生成httpClient
        httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
    }

    /**
     * 需要登录的方式,生成httpClient工具对象
     *
     * @param loginUrl 登录地址
     * @param reqMap   存储账号密码的map,如:
     *                 {
     *                 "userName":"admin"
     *                 ,"password":"123456"
     *                 }
     *                 创建对象:
     *                 Map<String,Object> reqMap = new HashMap<>();
     *                 reqMap.put("userName","admin");
     *                 reqMap.put("password","123456");
     */
    public HttpRequestUtil(String loginUrl, Map<String, Object> reqMap) {
        String jsonStr = JSONObject.toJSONString(reqMap);
        httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(loginUrl);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000)
                .setSocketTimeout(60000).build();
        httpPost.setConfig(requestConfig);
        httpPost.setHeader(CONTENT_TYPE, APPLICATION_JSON);
        httpPost.setHeader(DATA_ENCODING, StandardCharsets.UTF_8.name());
        try {
            httpPost.setEntity(new StringEntity(jsonStr));
            HttpResponse response = httpClient.execute(httpPost);
            System.out.println(EntityUtils.toString(response.getEntity()));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public String getToken (String loginUrl, Map<String, Object> reqMap) {
        String jsonStr = JSONObject.toJSONString(reqMap);
        httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(loginUrl);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000)
                .setSocketTimeout(60000).build();
        httpPost.setConfig(requestConfig);
        httpPost.setHeader(CONTENT_TYPE, APPLICATION_JSON);
        httpPost.setHeader(DATA_ENCODING, StandardCharsets.UTF_8.name());
        try {
            httpPost.setEntity(new StringEntity(jsonStr));
            HttpResponse response = httpClient.execute(httpPost);
            String s = EntityUtils.toString(response.getEntity());
            com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(s);
            String data = jsonObject.getString("data");
            return data;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 用户发起http请求,这里只演示post类型的请求
     *
     * @param url    请求的路径
     * @param reqMap 请求的参数
     * @return 接口响应的JSON数据
     */
    public String doPost(String url, Map<String, String> reqMap) {
        String jsonStr = JSONObject.toJSONString(reqMap);
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000)
                .setSocketTimeout(60000).build();
        //设置请求连接参数等
        httpPost.setConfig(requestConfig);
        //设置请求数据类型为JSON
        httpPost.setHeader(CONTENT_TYPE, APPLICATION_JSON);
        //设置编码
        httpPost.setHeader(DATA_ENCODING, StandardCharsets.UTF_8.name());
        CloseableHttpResponse httpResponse = null;
        try {
            httpPost.setEntity(new StringEntity(jsonStr));
            httpResponse = httpClient.execute(httpPost);
            HttpEntity entity = httpResponse.getEntity();
            return EntityUtils.toString(entity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return null;
    }
}

测试HttpTest类

import cn.hutool.http.HttpRequest;

import java.util.HashMap;
import java.util.Map;

public class HttpTest {
    public static void main(String[] args) {
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("account", "superAdmin");
        reqMap.put("password", CryptogramUtil.doSm2Encrypt("123456"));
        HttpRequestUtil httpRequestUtil = new HttpRequestUtil();
        String token = httpRequestUtil.getToken("http://localhost:82/login", reqMap);
        String value = "Bearer " + token;
        String resultStr = HttpRequest.get("http://localhost:82/sysOrg/page")
                .header("Authorization", value)
                .execute()
                .body();
        System.out.println(resultStr);
    }

}

标签:return,String,登录,http,接口,str,import,public,请求
From: https://www.cnblogs.com/zhu12/p/17270441.html

相关文章

  • HTTP Get请求的参数带空格如何处理
    在URL中,空格会被转义成%20,因此在GET请求的参数中,可以将空格替换为%20,或者使用加号(+)代替空格。这些特殊字符在URL中都有特殊的含义,因此需要进行编码,以便正确传递参......
  • 拼多多商品列表接口,关键词搜索拼多多商品接口,拼多多优惠券接口代码封装教程
    业务场景:作为全球最大的B2C电子商务平台之一,拼多多平台提供了丰富的商品资源,吸引了大量的全球买家和卖家。为了方便开发者接入拼多多平台,拼多多平台提供了丰富的API接口......
  • 抽象,接口以及内部类
    抽象类特点:不能new这个抽象类,只能靠他的子类实现:约束!抽象类中可以有普通方法抽象方法必须在抽象类中抽象的抽象:约束接口普通类:只有具体的实现抽象类:具体......
  • Jmeter处理接口返回值带反斜杠的数据
    目标:取joinUrl值,并对数据反斜杠处理,并保存到文件txt;  第一步:使用正则表达式提取器到返回值数据  第二步:使用BeanShellPostProcessor,处理返回值中的反斜杠;var......
  • Go语言:编写一个 WebsiteRacer 的函数,用来对比请求两个 URL 来「比赛」,并返回先响应的
    问题:你被要求编写一个叫做WebsiteRacer的函数,用来对比请求两个URL来「比赛」,并返回先响应的URL。如果两个URL在10秒内都未返回结果,那么应该返回一个error。......
  • Windows11跳过登录微软账户
    1、唤出cmd窗口在设置网络连接页面,按住“Shift”+"F10"键,或“Fn”+“Shift”+"F10"键唤出cmd窗口。 2、执行cmd命令在命令窗口输入“oobe\bypassnro.cmd”,按“Enter”......
  • 为什么现在是苹果采用19-pin小接口的最佳时机
    苹果的一贯作风,是以进步的名义来打破传统(有的时候是制定新标准)。其中包括其电脑设备抛弃了软盘驱动器以及光盘驱动器的设计。这不,最近传出的19-pin的接口将又掀起一股苹......
  • Map接口和常用方法
    Map接口实现类的特点(Put/Get)1、Map和Collection并列的存在,用于保存具有映射关系的数据:Key-Value2、Map中的key和value可以是任何引用类型的数据,会封装到HashMap$Node对象......
  • Redis-单一接口优化
    【性能优化】单一接口优化过程全记录(主要涉及Redis)接口优化过程记录 问题背景 某个接口耗时长(247ms),但里面逻辑不算复杂,只进行了简单的对象引用以及操作了多次Redis......
  • 优雅的接口防刷处理方案
     前言本文为描述通过Interceptor以及Redis实现接口访问防刷Demo这里会通过逐步找问题,逐步去完善的形式展示原理通过ip地址+uri拼接用以作为访问者访问接口区......