关于springboot:如何在spring-boot-使用-gitlab的Api

8次阅读

共计 5362 个字符,预计需要花费 14 分钟才能阅读完成。

前言

最近有我的项目需要是通过 gitlab 的 api 获取其中的数据。来记录一下我的踩坑的过程。
首先先尝试了获取 users 数据,即所有用户的数据。

这里是 gitlab 官网 API 文档 https://docs.gitlab.com/ee/ap…

这里说一下我刚开始的做法和老师倡议的做法。

最开始的做法

1. 获取 Admin access token

首先咱们须要获取 gitlab 的 Admin access token, 并且在申请的时候附带这个 token,gitlab 能力认证咱们的身份并返回数据。

1. 登录 GitLab。2. 登录后,点击右上角的头像图标而后抉择 Preferences。

3. 在 access token 界面就能够新建 token 了。

当你是 group 的管理员之后,就能够通过该 token 获取 users 了。

2. 应用 spring boot 单元测试发动申请

这里我应用了 apache 发动 http 申请,并应用了 fastjson 解决申请后所返回的 json 数据。

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.5.9</version>
</dependency>

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

以下是我测试的代码。来解释一下:

  1. 首先定义你的要申请的 url,格局如代码。也能够看官网文档。
  2. 构建 Http 申请类,并设置参数。参数必须要有 private_token。这里我加的 without_project_bots 能够过滤机器人 user。
  3. 应用 execute 函数发动 get 申请, 并接管返回的 json 数据。
  4. 从 json 数组转换成实体数组

这样就取得了咱们须要的数据。

@Test
  void getUsers() throws IOException, URISyntaxException {

    String url = "https://your gitlab address/api/v4/users";


    CloseableHttpClient httpclients = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet(url);
    // 设置参数信息
    URI uri = new URIBuilder(httpGet.getURI())
            .addParameter("private_token", "your amind token")
            .addParameter("without_project_bots", "true")
            .build();
    ((HttpRequestBase) httpGet).setURI(uri);

    // 发动申请
    CloseableHttpResponse response = httpclients.execute(httpGet);

    // 解决数据
    HttpEntity httpEntity = (HttpEntity) response.getEntity();
    String result =  EntityUtils.toString(httpEntity,"UTF-8");

    // 从 json 转换成实体
    final ObjectMapper objectMapper = new ObjectMapper();
    User[] langList = objectMapper.readValue(result, User[].class);

    logger.debug(String.valueOf(langList));

    response.close();}

期间我遇到的问题

1. java 须要增加证书

因为咱们发动的申请地址是 HTTPS 的,而 https 是对链接加了平安证书 SSL 的,如果服务器中没有相干链接的 SSL 证书,它就不可能信赖那个链接, 就会报 sun.security.validator.ValidatorException 谬误。

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

最开始我是把证书增加到本地中的,增加办法大略参考了如下博客
https://www.cnblogs.com/zoro-…

这样就把证书增加到了本地的 java 密钥库中。

然而这样只有本地可能失常应用这个我的项目。因为在并没有把证书增加到我的项目中。所以这也阐明了这种办法并不普适。

所以咱们须要把证书放在 src/main/resourse 中,部署 https。上面我会说一下如何增加。

2. 没有配置数据源

Error creating bean with name 'dataSourceScriptDatabaseInitializer' defined in class path resource [org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.class]

因为我只是在单元测试中测试,我的项目刚初始化,并没有连贯数据库,也就是并没有配置数据源。

所以因为没有向 Spring Boot 传递足够的数据来配置数据源,导致产生了该报错。

所以,如果咱们临时不须要数据源,就能够应用 exclude={DataSourceAutoConfiguration.class} 主动配置。这样就能够解决报错

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
public class NonlycodeApplication {
}

3. json 数据的属性多于实体的属性

在我申请到数据后,能够看到 gitlab 给咱们返回来的数据有很多。有 theme_id, note,is_admin 等信息。


然而,我定义的实体中目前只定义了几条须要的信息,比方 id ,name,username 等信息。

public class User implements Serializable {

  private static final long serialVersionUID = 1L;

  @Id
  private Long id;

  private String email = "";

  private Integer following = 0;

  private Integer followers = 0;

  private String name = "";

  private  String password = "yunzhi";

  @Column(nullable = false, unique = true)
  private String username;

在 json 转化数据的时候,遇到这种状况就会报错。并且报错说:not marked as ignorable。

所以咱们须要增加正文,把不须要的数据给疏忽掉。

我的解决办法是增加 @JsonIgnoreProperties(ignoreUnknown = true)
最初报错隐没。

@JsonIgnoreProperties(ignoreUnknown = true)
@Entity
public class User implements Serializable {

应用 RestTemplate 通过证书认证拜访 https

传统状况下在 java 代码里拜访 restful 服务,个别应用 Apache 的 HttpClient。如同我下面的代码。不过此种办法应用起来太过繁琐。spring 提供了一种简略便捷的模板类来进行操作,这就是 RestTemplate。

1. 获取证书

我参考了这篇文章来生成自签名证书。
https://www.baeldung.com/spri…

或者能够下载网站,参考这篇文章来创立密钥库
https://fullstackdeveloper.gu…

把生成的文件导入到我的项目 resourses/keystore 中

2. 配置 application.yml

填写一下本人配置的 password 和 alias 别名等

server:
  ssl:
    key-store-type: PKCS12
    key-store: classpath:keystore/baeldung.p12
    key-store-password: changeit
    key-alias: baeldung
  port: 8443

spring:
  security:
    user:
      name: root
      password: 1234

4. 配置 restTemplate

配置 restTemplate, 使其加载我的项目中的证书

  1. 新建 CustomConfiguration 类
  2. 重写 restTemplate() 函数

留神一下本人的文件名,以及方才本人设置的 key-store 明码

@Configuration
public class CustomConfiguration {

  @Bean
  RestTemplate restTemplate() throws Exception {SSLContext sslContext = new SSLContextBuilder()
            .loadTrustMaterial(new URL("file:src/main/resources/keystore/baeldung.p12"), "changeit".toCharArray()).build();
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext);
    HttpClient httpClient = HttpClients.custom()
            .setSSLSocketFactory(socketFactory)
            .build();
    HttpComponentsClientHttpRequestFactory factory =
            new HttpComponentsClientHttpRequestFactory(httpClient);
    return new RestTemplate(factory);
  }
}

3. 编写代码

controller 层:

@RestController
@RequestMapping("user")
public class UserController {

  @Autowired
  UserService userService;


  @GetMapping("/getUsers")
  @JsonView(GetUsersJsonView.class)
  public User[] getUsers() throws JsonProcessingException {return  this.userService.getUsers();
  }

  public class GetUsersJsonView {}}

service 层:
留神填写本人的 url 和 token。逻辑跟之前的代码差不多。

@Override
  public User[] getUsers() throws JsonProcessingException {
    String url = "https://your gitlab address /api/v4/users/" +
            "?private_token={private_token}&without_project_bots={without_project_bots}";

    final Map<String, String> variables = new HashMap<>();

    variables.put("private_token", "your token");
    variables.put("without_project_bots", "true");

    RestTemplate restTemplate = new RestTemplate();
    String response = restTemplate.getForObject(url, String.class, variables);


    // 从 json 转换成实体
    final ObjectMapper objectMapper = new ObjectMapper();
    User[] userList = objectMapper.readValue(response, User[].class);

    return userList;
  }

4. url 拜访

可能是因为 spring security, 须要登录。咱们输出 application.yml 中配置好的账号密码

4. 后果

可能是 jsonView 没配置好,页面显示空信息。之后再弄一下。

然而通过打断点打印, 显示成绩获取到了 gitlab 中的 users 信息。

正文完
 0