【发布时间】:2021-02-08 15:52:16
【问题描述】:
您好,我想制作一个非常简单的应用程序,在控制台中打印 openweathermap.org API 答案。我认为它应该可以工作,但是当我要在浏览器中访问地址时,我得到了 Whitelabel 错误页面,而控制台中什么也没有。我上了两节课。主要:
package com.example.restTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.Arrays;
@SpringBootApplication
public class RestTemplateApplication {
public static void main(String[] args) {
SpringApplication.run(RestTemplateApplication.class, args);
}
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
和控制器:
package com.example.restTemplate.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.Arrays;
@RestController
public class ConsumeWebService {
@Autowired
RestTemplate restTemplate;
@RequestMapping(value = "localhost:8080/weather")
public void printWeather() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>(headers);
System.out.println(restTemplate.exchange("http://api.openweathermap.org/data/2.5/weather?q=London,uk&myAPIKey",
HttpMethod.GET, entity, String.class).getBody());
}
}
当然,我没有把我真正的 API 密钥放在这里,我应该在参数中声明城市和密钥,但我以后会考虑的。现在我只想在控制台中获得一个简单的输出,我们将不胜感激您的帮助。
【问题讨论】:
标签: api spring-mvc resttemplate