集册 Java实例教程 创建Json对象并发布到URL

创建Json对象并发布到URL

欢马劈雪     最近更新时间:2020-01-02 10:19:05

339
创建Json对象并发布到URL

/*
来 自*
 时 代 J a v a 公 众 号
*/


import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.URISyntaxException;

import java.net.URL;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;


import org.json.JSONArray;

import org.json.JSONObject;


public class Main {/** 来 自 时 代 J a v a - nowjava.com**/

    class JThread extends Thread {

        String result = "";

        URL uri;


        public JThread(String url) throws URISyntaxException,

                MalformedURLException {

            uri = new URL(url);


        }


        @Override

        public void run() {

            try {

                HttpURLConnection con = (HttpURLConnection) uri

                        .openConnection();

                con.setRequestMethod("GET");


                con.connect();

                int status = con.getResponseCode();

                if (status == HttpURLConnection.HTTP_OK) {

                    BufferedReader br = new BufferedReader(

                            new InputStreamReader(con.getInputStream(),

                                    "iso-8859-1"), 1024);

                    StringBuffer sb = new StringBuffer();

                    String line = null;

                    while ((line = br.readLine()) != null) {

                        sb.append(line).append('\n');

                    }

                    br.close();

                    result = sb.toString();

                }


            } catch (IOException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }

            ArrayList<HashMap<String, String>> list = new ArrayList<>();

            JSONObject json = new JSONObject(result);

            JSONArray earthquakes = json.getJSONArray("earthquakes");

            for (Object object : earthquakes) {

                JSONObject e = (JSONObject) object;

                HashMap<String, String> map = new HashMap<>(e.length());

                map.put("datetime", e.getString("datetime"));

                map.put("depth", e.getDouble("depth") + "");

                map.put("lng", e.getDouble("lng") + "");


                map.put("src", e.getString("src"));

                map.put("eqid", e.getString("eqid"));

                map.put("magnitude", e.getDouble("magnitude") + "");

                map.put("lat", e.getDouble("lat") + "");


                list.add(map);

            }


            System.out.println(list);

        }


    }


    public static 
展开阅读全文