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

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 urlStr= "第三方url接口";
	         String jsonString = null;
             try {
		            URL url = new URL(urlStr);
		            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		            conn.setRequestMethod("GET");
		            conn.connect();
		            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
		            String line = "";
		            StringBuffer buffer = new StringBuffer();
		            while ((line = reader.readLine() )!= null){
		                buffer.append(line);
		            }
		            reader.close();
		            conn.disconnect();
		             jsonString = buffer.toString();
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
         PrintWriter printWriter = null;
         try {
             printWriter = response.getWriter();
         } catch (IOException e) {
             e.printStackTrace();
         }
         printWriter.print(jsonString );
    }
    

二、使用post方式调用

//以后更新

三、第三方返回的是一个xml文件(get方式)

protected void service(HttpServletRequest request, HttpServletResponse response){
    response.setCharacterEncoding("utf-8");
    String urlStr = "第三方url接口";
    String result = getInfoByHttp(urlStr);
    PrintWriter printWriter = null;
    try {
        printWriter = response.getWriter();
    } catch (IOException e) {
        e.printStackTrace();
    }
    printWriter.print(result);
}
    public static String getInfoByHttp(String url) {
        HttpGet httpGet = new HttpGet(url);
        HttpClient httpClient = new DefaultHttpClient();
        String result = "";
        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);
            result = getJsonStringFromGZIP(httpResponse);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    private static String getJsonStringFromGZIP(HttpResponse response) {
        String jsonString = null;
        try {
            InputStream is = response.getEntity().getContent();
            BufferedInputStream bis = new BufferedInputStream(is);
            bis.mark(2);
            // 取前两个字节
            byte[] header = new byte[2];
            int result = bis.read(header);
            // reset输入流到开始位置
            bis.reset();
            // 判断是否是GZIP格式
            int headerData = getShort(header);
            if (result != -1 && headerData == 0x1f8b) {
                is = new GZIPInputStream(bis);
            } else {
                is = bis;
            }
            InputStreamReader reader = new InputStreamReader(is, "utf-8");
            char[] data = new char[100];
            int readSize;
            StringBuffer sb = new StringBuffer();
            while ((readSize = reader.read(data)) > 0) {
                sb.append(data, 0, readSize);
            }
            jsonString = sb.toString();
            bis.close();
            reader.close();
        } catch (Exception e) {
        }
        return jsonString;
    }
    private static int getShort(byte[] data) {
        return (int) ((data[0] << 8) | data[1] & 0xFF);
    }
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、付费专栏及课程。

余额充值