java调用第三方接口代码,返回json/xml数据并可以输出到页面(含pom)

本文介绍了如何使用Java进行HTTP调用,包括GET和POST方式,以及如何处理接收到的XML和JSON格式的数据。示例代码详细展示了在POM文件配置和接口调用过程。
摘要由CSDN通过智能技术生成

pom文件

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

    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient-cache</artifactId>
      <version>4.5</version>
    </dependency>

    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpmime</artifactId>
      <version>4.3.2</version>
    </dependency>

一、使用get方式调用(返回json)

     protected void service(HttpServletRequest request, HttpServletResponse response){
	         response.setCharacterEncoding("utf-8");
	         response.setContentType("application/json; charset=utf-8");
	         String urlS
1. 引入依赖 在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.62</version> </dependency> ``` 2. 创建Feign接口 创建一个Feign接口来定义调用第三方天气预报接口的方法,该接口使用`@FeignClient`注解来指定要调用的服务名和服务地址。 ```java @FeignClient(name = "weather", url = "http://www.weather.com.cn") public interface WeatherClient { @GetMapping("/data/sk/{cityCode}.html") String getWeather(@PathVariable("cityCode") String cityCode); } ``` 3. 创建Controller 创建一个Controller来处理前端的请求,该Controller使用`@RestController`注解来指定返回的结果是JSON格式的数据。 ```java @RestController @RequestMapping("/weather") public class WeatherController { @Autowired private WeatherClient weatherClient; @GetMapping("/{cityCode}") public String getWeather(@PathVariable("cityCode") String cityCode) { String result = weatherClient.getWeather(cityCode); // 处理返回结果 return result; } } ``` 4. 测试 启动SpringBoot应用,访问`http://localhost:8080/weather/101210101`,即可查看北京市的天气预报信息。 返回的结果如下所示: ```json {"weatherinfo":{"city":"北京","cityid":"101010100","temp":"-2","WD":"西南风","WS":"2级","SD":"26%","AP":"1022hPa","njd":"暂无实况","WSE":"2","time":"17:55","sm":"1.1","isRadar":"1","Radar":""}} ``` 通过以上步骤,我们成功地使用Feign技术调用第三方天气预报接口,并以JSON格式显示给前端。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值