In the development of spring-Boot project, there is a requirement that the code of this module needs to access the external module interface or external URL link, such as calling external map API or weather API.

Conclusion: Spring Boot – Accessing an external interface Solution 1: Use native Http request Solution 2: Use Feign to consume Solution 3: Get forentity (Stringurl,Class responseType,Object… UrlVariables) getForEntity(URI URL,Class responseType) getForObject Post request

Scheme 1: Use the native Http request. Use the native Http request in the code as follows:

@requestMapping (“/doPostGetJson”)public String doPostGetJson() throws ParseException {// Convert the data to be sent to a String in JSON format JsonText = “{id: 1}”; JSONObject json = (JSONObject) JSONObject.parse(jsonText); JSONObject sr = this.doPost(json); System.out.println(” return argument: “+ sr); return sr.toString(); }public static JSONObject doPost(JSONObject date) { HttpClient client = HttpClients.createDefault(); / / to invoke the interface methods String url = “http://192.168.1.101:8080/getJson”; HttpPost post = new HttpPost(url); JSONObject jsonObject = null; try { StringEntity s = new StringEntity(date.toString()); s.setContentEncoding(“UTF-8”); s.setContentType(“application/json”); post.setEntity(s); post.addHeader(“content-type”, “text/xml”); HttpResponse res = client.execute(post); String response1 = EntityUtils.toString(res.getEntity()); System.out.println(response1); if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String result = EntityUtils.toString(res.getEntity()); // Return json format: jsonObject = jsonObject.parseObject (result); } } catch (Exception e) { throw new RuntimeException(e); } return jsonObject; } Add dependencies to the Maven project

Org. Springframework. Cloud spring – the cloud – starter – feign 1.2.2. RELEASE 2, write interface, placed in the service layer

DecisionEngine here. The url is configured in the properties of the is the IP address and port number decisionEngine url = http://10.2.1.148:3333/decision/person is the interface name

@FeignClient(url = “${decisionEngine.url}”,name=”engine”)public interface DecisionEngineService {@requestMapping (value=”/decision/person”,method= requestMethod.post) public JSONObject getEngineMesasge(@RequestParam(“uid”) String uid,@RequestParam(“productCode”) String productCode); } add @enableFeignClients to the Java startup class

@ EnableFeignClients / / see here @ EnableDiscoveryClient @ SpringBootApplication @ EnableResourceServerpublic class Application implements CommandLineRunner { private static final Logger LOGGER = LoggerFactory.getLogger(Application.class); @Autowired private AppMetricsExporter appMetricsExporter; @Autowired private AddMonitorUnitService addMonitorUnitService; public static void main(String[] args) { new SpringApplicationBuilder(Application.class).web(true).run(args); }} 4, call the interface in the code

@Autowiredprivate DecisionEngineService decisionEngineService ; / /… decisionEngineService.getEngineMesasge(“uid” , “productCode”); Solution 3: Use the RestTemplate method In spring-Boot development, RestTemplate also provides an external access API. This section mainly describes the use of Get and Post methods. The Get request provides two types of interfaces getForObject and getForEntity. GetForEntity provides the implementation of the following three methods.

GetForEntity (Stringurl,Class responseType,Object… (urlVariables) This method provides three parameters (url = the address of the request, responseType = the wrapper type of the body of the response, urlVariables).

// http://USER-SERVICE/user? name={name)RestTemplate restTemplate=new RestTemplate(); Map

params=new HashMap<>(); params.put(“name”,”dada”); //ResponseEntity responseEntity=restTemplate.getForEntity(“http://USERSERVICE/user? name={name}”,String.class,params); Get request — getForEntity(URI URL,Class responseType) This method uses a URI object instead of the URL and urlVariables parameters to specify the access address and parameter binding. A URI is a class in the JDK Java.net package that represents a Uniform Resource Identifier reference. For reference:
,string>

RestTemplate restTemplate=new RestTemplate(); UriComponents uriComponents=UriComponentsBuilder.fromUriString(“http://USER-SERVICE/user?name={name}”) .build() .expand(“dodo”) .encode(); URI uri=uriComponents.toUri(); ResponseEntity responseEntity=restTemplate.getForEntity(uri,String.class).getBody(); Get request – getForObject getForObject method for further encapsulation of getForEntity is understandable, it of the request of the HTTP response body through HttpMessageConverterExtractor object into the body content, The implementation request returns the wrapped object content directly. The getForObject methods are as follows:

getForObject(String url,Class responseType,Object… urlVariables)getForObject(String url,Class responseType,Map urlVariables)getForObject(URI url,Class responseType) Post The Post request provides three methods, postForEntity, postForObject, and postForLocation. There are three methods for each method, postForEntity method is used as follows:

RestTemplate restTemplate=new RestTemplate(); User user=newUser(“didi”,30); ResponseEntity responseEntity=restTemplate.postForEntity(“http://USER-SERVICE/user”,user,String.class); Responseentity.getbody (); responseEntity.getBody(); responseEntity.getBody(); PostForEntity has the following three overloaded methods

postForEntity(String url,Object request,Class responseType,Object… uriVariables)postForEntity(String url,Object request,Class responseType,Map uriVariables)postForEntity(URI url,Object Request, Class responseType) and the other arguments in postForEntity are pretty much the same as for getForEntity and I’m not going to go into that here.

Finally, if you feel this good, trouble on forward, thank you all for your support for more information about the Spring Boot ~ please click below document can free access to https://shimo.im/docs/pVhDCpYqdRTqWRqq/.