HTTP请求百度日期API

package com.httpUrl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class JsonTest {
    public static void main(String[] args) throws IOException {
        //String url = "https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query=2020%E5%B9%B43%E6%9C%88&resource_id=6018&format=json";
        //创建http请求客户端
        CloseableHttpClient build = HttpClientBuilder.create().build();
        //发送get请求
        HttpGet httpGet = new HttpGet("https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query=2020%E5%B9%B43%E6%9C%88&resource_id=6018&format=json");
        //执行发送Get请求
        CloseableHttpResponse execute = build.execute(httpGet);
        //创建list集合存放日期
        List data_List = new ArrayList<>();
        //判断响应的状态是否为:200
        if (execute.getStatusLine().getStatusCode()==200){
            //获取响应的实体
            HttpEntity entity = execute.getEntity();
            System.out.println(entity);
            //设置响应编码格式
            String context = EntityUtils.toString(entity, "utf-8");
            //将字符串转换为json格式
            JSONObject parseContext = (JSONObject) JSONObject.parse(context);
            //获取json数据里的data数组
            JSONArray data = parseContext.getJSONArray("data");
            JSONArray holiday = getHoliday("holiday", data);
            JSONArray list = getHoliday("list", (JSONArray) holiday);
            //遍历list
            for (Object o : list) {
                String sql = o.toString();
                JSONObject jsonObject = (JSONObject) JSONObject.parse(sql);
                String date = jsonObject.getString("date");
                data_List.add(date);
            }

            System.out.println(data_List);
        }
    }

    /**
     * 根据key值获取json的array数组数据
     * @param param
     * @param arr
     * @return
     */
    public static JSONArray getHoliday(String param, JSONArray arr){
        JSONArray key = null;
        for (Object datum : arr) {
            String data_Str = datum.toString();
            JSONObject data_Json = (JSONObject) JSONObject.parse(data_Str);
            key = data_Json.getJSONArray(param);
        }
        return key;
    }
}

 

你可能感兴趣的:(java)