Java获取代理地址和端口

使用了gson解析数据

package online.geekgalaxy.test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import com.google.gson.*;


public class jsonAPI {

    public static void main(String[] args) throws Exception {

        //外接口路径
        String urlStr="http://31f.cn/api/httpAll/";
        //链接URL
        URL url=new URL(urlStr);
        //返回结果集
        StringBuffer document = new StringBuffer();
        //创建链接
        URLConnection conn = url.openConnection();
        //读取返回结果集
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
        String line = null;
        while ((line = reader.readLine()) != null){
            document.append(line);
        }
        reader.close();
        System.out.println(document);
        JsonParser parse =new JsonParser();  //创建json解析器
        try {
            JsonObject json=(JsonObject) parse.parse(document.toString());  //创建jsonObject对象
            JsonArray list = json.get("proxy").getAsJsonArray();
            for (JsonElement element:list) {
                JsonObject childjson = (JsonObject) parse.parse(element.toString());
                String ip = childjson.get("ip").getAsString();
                Integer port = childjson.get("port").getAsInt();
                System.out.println("IP: " + ip);
                System.out.println("Port: " + String.valueOf(port));
            }
        } catch (JsonIOException e) {
            e.printStackTrace();
        }
    }

}


你可能感兴趣的:(编程人生,java,json)