1. 程式人生 > 實用技巧 >Retrofit:後端傳送HTTP請求

Retrofit:後端傳送HTTP請求

引入Maven依賴:

<dependency>
     <groupId>com.github.lianjiatech</groupId>
     <artifactId>retrofit-spring-boot-starter</artifactId>
     <version>2.2.5</version>
</dependency>

定義HTTP介面:

import com.alibaba.fastjson.JSONObject;
import com.github.lianjiatech.retrofit.spring.boot.annotation.RetrofitClient;
import retrofit2.http.*; import java.util.Map; @RetrofitClient(baseUrl = "https://api.doctorxiong.club") public interface httpApi { @GET("/v1/fund?code=202015,007339") Map<String,Object> httpGetTest(); @POST("/v1/fund/rank") Map<String,Object> httpPostTest(@Body JSONObject jsonObject); }

將HTTP介面注入Service中使用:

@Service
public class testServiceImpl {
    @Autowired
    private httpApi httpApi;

    @Scheduled(cron = "*/5 * * * * ?")
    public void TestTask() {
        JSONObject jsonObject = new JSONObject();
        List<Object> list = new ArrayList<>();
        list.add(
"zs"); jsonObject.put("fundType",list); jsonObject.put("sort","z"); List<Object> list1 = new ArrayList<>(); list1.add("80000248"); jsonObject.put("fundCompany",list1); jsonObject.put("pageIndex",1); jsonObject.put("pageSize",10); System.out.println(jsonObject); Map<String, Object> getMap = httpApi.httpGetTest(); System.out.println(getMap); Map<String, Object> postMap = httpApi.httpPostTest(jsonObject); System.out.println(postMap); } }

可使用的HTTP網址:https://www.doctorxiong.club/api/#api-Fund-fund

Retrofit 的GitHub官網:https://github.com/LianjiaTech/retrofit-spring-boot-starter

Retrofit 的官網文件:https://square.github.io/retrofit/#introduction