Java向api接口发送请求,获取json数据并解析

  • 采用的是和风天气的降水接口,因为api需要付费,所以就不把自己的key放出来了。
  • json解析工具用的是阿里巴巴的fastjson。用了很多次的System.out.println(),只是为了测试。
  • 代码如下:
package json;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class Demo2
{
    public static void main(String[] args) throws Exception
    {
        //参数字符串,如果拼接在请求链接之后,需要对中文进行 URLEncode   字符集 UTF-8
        String param = "location=108.62 ,21.95&key=写你自己的key";
        StringBuilder sb = new StringBuilder();
        InputStream is = null;
        BufferedReader br = null;
        PrintWriter out = null;
        try {
            //接口地址
            String url = "https://api.heweather.net/s6/weather/grid-minute";
            URL    uri = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) uri.openConnection();
            connection.setRequestMethod("POST");
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(10000);
            connection.setRequestProperty("accept", "*/*");
            //发送参数
            connection.setDoOutput(true);
            out = new PrintWriter(connection.getOutputStream());
            out.print(param);
            out.flush();
            //接收结果
            is = connection.getInputStream();
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String line;
            //缓冲逐行读取
            while ( ( line = br.readLine() ) != null )
            {
                sb.append(line);
            }
            String backStr=sb.toString();
            System.out.println(backStr);
            JSONObject jsonObject = JSONObject.parseObject(backStr);
            JSONArray heWeather6 = jsonObject.getJSONArray("HeWeather6");
            System.out.println(heWeather6);
            JSONObject jsonObject1 = heWeather6.getJSONObject(0);
            System.out.println(jsonObject1);
            JSONObject basic = jsonObject1.getJSONObject("basic");
            System.out.println(basic);
            String parent_city = basic.getString("parent_city");
            System.out.println(parent_city);
            String lon = basic.getString("lon");
            System.out.println(lon);
            String lat = basic.getString("lat");
            System.out.println(lat);

            System.out.println("--------------");
            JSONArray pcpn_5m = jsonObject1.getJSONArray("pcpn_5m");
            for (int i = 0; i < pcpn_5m.size(); i++)
            {
                JSONObject jsonObject2 = pcpn_5m.getJSONObject(i);
                System.out.println(jsonObject2);

            }
        } catch ( Exception e )
        {
            System.out.println(e);
        } finally
        {
            //关闭流
            try
            {
                if(is!=null)
                {
                    is.close();
                }
                if(br!=null)
                {
                    br.close();
                }
                if (out!=null)
                {
                    out.close();
                }
            } catch ( Exception ignored )
            {
                System.out.println(ignored);
            }
        }


    }
}

  • 运行结果如下图:
    在这里插入图片描述
Java可以使用HttpURLConnection或者HttpClient库来发送HTTP请求获取API数据,并使用JSON解析返回的JSON数据。 使用HttpURLConnection发送GET请求的示例代码如下: ```java import java.net.HttpURLConnection; import java.net.URL; import java.io.BufferedReader; import java.io.InputStreamReader; // 发送HTTP GET请求获取API数据 public String getApiData(String url) { StringBuilder result = new StringBuilder(); try { URL apiUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) apiUrl.openConnection(); conn.setRequestMethod("GET"); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { result.append(line); } rd.close(); } catch (Exception e) { e.printStackTrace(); } return result.toString(); } ``` 使用JSON解析返回的JSON数据的示例代码如下: ```java import org.json.JSONArray; import org.json.JSONObject; // 解析返回的JSON数据 public void parseJson(String jsonData) { JSONObject jsonObj = new JSONObject(jsonData); int code = jsonObj.getInt("code"); String message = jsonObj.getString("message"); JSONArray data = jsonObj.getJSONArray("data"); for(int i=0;i<data.length();i++){ JSONObject obj = data.getJSONObject(i); String name = obj.getString("name"); int age = obj.getInt("age"); System.out.println(name + "," + age); } } ``` 其中,`getApiData`方法用于发送GET请求获取API数据,`parseJson`方法用于解析返回的JSON数据。请根据API的具体情况进行调整。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值