调取第三方api获取数据的工具类

使用:直接第三方接口作为参数传进来即可

package com.jeesite.modules.train.util;


import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;


/**
 * 通过api接口获取json方法的封装
 *
 * @author ty
 * @version 2020-06-05
 */
@Component
public class ObtainJsonApiUtil {


    public  JSONObject obtainJsonApi(String urlLink) {
        JSONObject json = new JSONObject();
        String urls =urlLink ;
        URL url = null;
        //打开和url之间的连接
        HttpURLConnection conn = null;
        PrintWriter out = null;
        JSONObject jsonResult = null;
        try {
            url = new URL(urls);
            conn = (HttpURLConnection) url.openConnection();
            //请求方式
            conn.setRequestMethod("GET");
            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            //获取连接
            conn.connect();
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String str = "";
            while ((str = br.readLine()) != null) {
                jsonResult = JSONObject.parseObject(str);
            }
            //关闭流
            is.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭连接
            conn.disconnect();
        }
        return jsonResult;
    }

}
 

你可能感兴趣的:(调取第三方api获取数据的工具类)