openfeign+retronfit http 访问
一个简单记录
maven 依赖
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-gson</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-core</artifactId>
<version>11.0</version>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-gson</artifactId>
<version>11.0</version>
</dependency>
openfeign参考代码
private static void openFeign() {
GitHub github = Feign.builder()
.decoder(new GsonDecoder())
.target(GitHub.class, "https://api.github.com");
List<Contributor> contributors = github.contributors("OpenFeign", "feign");
for (Contributor contributor : contributors) {
System.out.println(contributor.login + " (" + contributor.contributions + ")");
}
}
package com.dalong;
import feign.Param;
import feign.RequestLine;
import java.util.List;
/**
*
* github api
*/
public interface GitHub {
/**
* contributors 获取
* @param owner
* @param repo
* @return
*/
@RequestLine("GET /repos/{owner}/{repo}/contributors")
List<Contributor> contributors(@Param("owner") String owner, @Param("repo") String repo);
/**
* issue 请求获取
* @param issue
* @param owner
* @param repo
*/
@RequestLine("POST /repos/{owner}/{repo}/issues")
void createIssue(Issue issue, @Param("owner") String owner, @Param("repo") String repo);
}
retrofit2
package com.dalong;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;
import java.util.List;
/**
*
* github api
*/
public interface GitHub2 {
/**
* contributors 获取
* @param owner
* @param repo
* @return
*/
@GET("/repos/{owner}/{repo}/contributors")
Call<List<Contributor>> contributors(@Path("owner") String owner, @Path("repo") String repo);
/**
* issue 请求获取
* @param issue
* @param owner
* @param repo
*/
@POST("/repos/{owner}/{repo}/issues")
void createIssue(@Body Issue issue, @Path("owner") String owner, @Path("repo") String repo);
}
private static void retrofit() throws IOException {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
// Fetch and print a list of the contributors to this library.
GitHub2 gitHub2 = retrofit.create(GitHub2.class);
Call<List<Contributor>> contributors2 = gitHub2.contributors("OpenFeign", "feign");
for (Contributor contributor : contributors2.execute().body()) {
System.out.println("github2");
System.out.println(contributor.login + " (" + contributor.contributions + ")");
}
}
参考资料
https://github.com/square/retrofit
https://github.com/OpenFeign/feign
https://mvnrepository.com/artifact/com.squareup.retrofit2
https://mvnrepository.com/artifact/io.github.openfeign