JAVA免费的天气预报调用代码

    String param = "version=v1";
    StringBuilder sb = new StringBuilder();
    InputStream is = null;
    BufferedReader br = null;
    PrintWriter out = null;
    try {
        //接口地址
        String url = "https://www.tianqiapi.com/api/";
        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);
        }
        System.out.println(sb.toString());
    } catch ( Exception ignored ) {
    } finally {
        //关闭流
        try {
            if(is!=null){
                is.close();
            }
            if(br!=null){
                br.close();
            }
            if (out!=null){
                out.close();
            }
        } catch ( Exception ignored ) {}
    }

查看JSON响应结果

发布了43 篇原创文章 · 获赞 38 · 访问量 12万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 书香水墨 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览