第一步: 添加依赖
<dependency>
<groupId>com.squareup.retrofit</groupId>
<artifactId>retrofit</artifactId>
<version>1.9.0</version>
</dependency>
这里使用的是1.9.0
第二部:添加配置RestAdapterConfig.java
package com.lxj.thread.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import retrofit.RestAdapter;
@Configuration
public class RestAdapterConfig {
/**
* 获取RestAdapter单例Bean
*
* @return
*/
@Bean
public RestAdapter getRestAdapter() {
/**
* setEndpoint("http://127.0.0.1:31111"):指定基本的URL,
* API接口中的URL是相对于该URL的路径的,
* 不能少了协议名,例如写成:localhost:8081就不行
*/
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint("http://127.0.0.1:31111")
.build();
return adapter;
}
}
说明:
这里的URL是指 你所要调用的第三方接口的URL 只需要ip和port。
第三步:添加配置RetrofitAPI,指定调用远程服务方法
package com.lxj.thread.apiservice;
import retrofit.http.GET;
import retrofit.http.POST;
import java.util.List;
public interface RetrofitAPI {
/**
* GET请求带查询参数
*/
@GET("/API/getRetrofitAPI")
String getRetrofitAPI();
/**
* POST请求
*/
@POST("/API/postRetrofitAPI")
List<String> postRetrofitAPI();
}
该类指定了第三方远程服务的方法的基本路径与参数以及返回值
第四步:添加配置RetrofitAPIConfig,构建RetrofitAPI
package com.lxj.thread.config;
import com.lxj.thread.apiservice.RetrofitAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import retrofit.RestAdapter;
@Configuration
public class RetrofitAPIConfig {
@Autowired
private RestAdapter adapter;
@Bean
public RetrofitAPI getRetrofitAPI() {
return adapter.create(RetrofitAPI.class);
}
}
之后的五六两步就是创建controller层和service层
第五步:创建Controller层
@Autowired
private RetrofitService retrofitService;
@GetMapping("/getRetrofitAPI")
public String getRetrofitAPI() {
return retrofitService.getRetrofitAPI();
}
@PostMapping("/postRetrofitAPI")
public List<String> postRetrofitAPI() {
return retrofitService.postRetrofitAPI();
}
第六步:创建Service 层
package com.lxj.thread.apiservice.impl;
import com.lxj.thread.apiservice.RetrofitAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class RetrofitService {
@Autowired
private RetrofitAPI retrofitAPI;
public String getRetrofitAPI() {
return String.getRetrofitAPI();
}
public List<String> postRetrofitAPI() {
return String.postRetrofitAPI();//测试post请求
}
}