springboot应用查询城市天气

创建springboot应用

  1. 基于maven创建一个springboot应用,pom信息如下,注意添加了httpclient:
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns=“http://maven.apache.org/POM/4.0.0” xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”

xsi:schemaLocation=“http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”>

4.0.0

org.springframework.boot

spring-boot-starter-parent

2.1.2.RELEASE

com.bolingcavalry

weatherservice

0.0.1-SNAPSHOT

weatherservice

Demo project for Spring Boot

<java.version>1.8</java.version>

org.springframework.boot

spring-boot-starter-web

org.apache.httpcomponents

httpclient

4.5.7

org.springframework.boot

spring-boot-starter-test

test

org.springframework.boot

spring-boot-maven-plugin

  1. 启动类如下:

package com.bolingcavalry.weatherservice;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class WeatherserviceApplication {

public static void main(String[] args) {

SpringApplication.run(WeatherserviceApplication.class, args);

}

}

创建配置类

创建一个配置类,这里注意要使用HttpComponentsClientHttpRequestFactory作为RestTemplate构造方法的入参,这样才能支持gzip压缩的response,否则得到的就是乱码:

package com.bolingcavalry.weatherservice;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;

import org.springframework.http.converter.StringHttpMessageConverter;

import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

@Configuration

public class WeatherConfig {

@Bean

public RestTemplate restTemplate(){

RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());

restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));

return restTemplate;

}

}

创建controller

创建一个controller来接收web请求,然后发起气象服务网站发起天气查询:

package com.bolingcavalry.weatherservice.controller;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.*;

import org.springframework.web.bind.annotation.PathVariable;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值