天天看點

springboot項目用RestTemplate調用第三方接口

1. 導入依賴

<dependency>
   <groupId>org.apache.httpcomponents</groupId>
   <artifactId>httpclient</artifactId>
   <version>4.5.2</version>
</dependency>
           

2. 建立配置類

import java.nio.charset.StandardCharsets;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {
	 	@Bean
	    public RestTemplate restTemplate(){
	 		RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
	 		restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
	        return restTemplate;
	    }
	 
	    @Bean
	    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
	        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
	        factory.setConnectTimeout(15000);
	        factory.setReadTimeout(5000);
	        return factory;
	    }
}
           

3. Controller

import java.io.IOException;
import java.net.URI;
import java.util.Map;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

@Controller
public class SysTestController {
	 	
	 	@Autowired
	    private RestTemplate restTemplate;
	 	
	    @GetMapping("/queryWeather")
	    @ResponseBody
	    public String QueryWeather(String city) {
	        String apiURL = "http://wthrcdn.etouch.cn/weather_mini?city=" + city;
	        ResponseEntity<String> responseEntity = restTemplate.getForEntity(apiURL, String.class);
	 
	        if (200 == responseEntity.getStatusCodeValue()) {
	            return responseEntity.getBody();
	        } else {
	            return "error with code : " + responseEntity.getStatusCodeValue();
	        }
	    }
	    
	    
}
           

4. html

function queryWeather(){
			var city=$("#city").val();
			$.ajax({
				type:"GET",
				url: prefix + "/queryWeather",
				dataType:"json",
				data:{city:city},
				async:false,
				success:function (result) {
					debugger;
					console.log(result.data.forecast);
					var div = document.getElementById("msg"); 
					var length=result.data.forecast.length;
					for(var i=0;i<length;i++){
						var div2 = document.createElement("label");
						div2.innerText = result.data.forecast[i].date;
						div.appendChild(div2);
					}
					
				},
				error :function(errorMsg) {
					alert("擷取背景資料失敗!");
				}
			});
		}