Java visit http external interfaces

As the demand needs to access other external interfaces in the background so I wrote a method
first add maven dependent

		<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);
	} 
	
}

Test Results
Here Insert Picture Description
Here Insert Picture Description

Guess you like

Origin blog.csdn.net/weixin_42118284/article/details/90903993