请使用java语言,使用RestTemplate类,调用http://t.weather.itboy.net/api/weather/city/101110101并接收返回值,然后把返回值解析成json
时间: 2023-09-15 15:17:29 浏览: 118
好的,以下是Java代码,使用RestTemplate类调用http://t.weather.itboy.net/api/weather/city/101110101并解析返回值成json:
```java
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;
public class WeatherAPIExample {
public static void main(String[] args) throws Exception {
RestTemplate restTemplate = new RestTemplate();
String url = "http://t.weather.itboy.net/api/weather/city/101110101";
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
String responseBody = response.getBody();
System.out.println("Response Body: " + responseBody);
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> jsonMap = objectMapper.readValue(responseBody, Map.class);
System.out.println("City: " + jsonMap.get("city"));
}
}
```
这段代码使用了Spring的RestTemplate类来发送GET请求,并接收服务器返回的JSON数据。然后使用Jackson库的ObjectMapper类将JSON解析成Map对象,从中获取城市名并输出。
阅读全文