由于需求需要在后台访问 其他外部接口 所以写了个方法
首先添加maven依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
Service
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
/**
* @author 作者 : 小布
* @version 创建时间 : 2019年6月5日 下午3:42:49
* @explain 类说明 :
*/
@Service
public class HttpService {
public String httpRequest(String url,HttpMethod method){
RestTemplate template = new RestTemplate();
ResponseEntity<String> response = template.getForEntity(url, String.class);
return response.getBody();
}
}
Controller
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
/**
* @author 作者 : 小布
* @version 创建时间 : 2019年6月5日 下午3:42:29
* @explain 类说明 :
*/
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@Api(tags = "外部相关接口")
@RequestMapping("/http")
public class HttpController {
@Autowired
private HttpService httpService;
@PostMapping("/httpRequestTest")
@ApiOperation(value="测试外部接口")
public String httpRequestTest(@RequestBody Map<String, Object> map){
return httpService.httpRequest((String)map.get("url"), HttpMethod.GET);
}
}
测试结果