java解析数据接口获取json对象

使用了Postman这个工具来解析,也获取了json对象,但后也发现,它没法直接连接数据库,也就是说这些数据不能直接存入数据库,经过查询,使用node.js作为中介可以解决这个问题,后又发现,连接后一次只能向数据库post一个对象,后就直接使用java解析吧!
使用常用HTTP方法的POST和GET为例:

1、先看get方法
public static JsonObject getPath(String requestUrl){
String res="";
JsonObject object = null;
StringBuffer buffer = new StringBuffer();
try{
URL url = new URL(requestUrl);//获取url
HttpURLConnection urlCon= (HttpURLConnection)url.openConnection();//得到链接
if(200==urlCon.getResponseCode()){//如果资源存在
InputStream is = urlCon.getInputStream();//得到网络的输入流
InputStreamReader isr = new InputStreamReader(is,“utf-8”);//编码格式
BufferedReader br = new BufferedReader(isr);//存入Buffer缓冲区

            String str = null;
            while((str = br.readLine())!=null){
                buffer.append(str);
            }
            br.close();
            isr.close();
            is.close();
            res = buffer.toString();
            JsonParser parse =new JsonParser();
            object = (JsonObject) parse.parse(res);
        }
    }catch(IOException e){
        e.printStackTrace();
    }
    return object;
}

2、POST方法

public static JsonObject postJson(String path,String post){
URL url = null;
try {
url = new URL(path);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod(“POST”);// 提交模式
conn.setConnectTimeout(10000);//连接超时 单位毫秒
conn.setReadTimeout(2000);//读取超时 单位毫秒
// 发送POST请求必须设置如下两行
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
// 获取URLConnection对象对应的输出流
PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
// 发送请求参数
printWriter.write(post);//post的参数 xx=xx&yy=yy
// flush输出流的缓冲
printWriter.flush();
//开始获取数据
BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len;
byte[] arr = new byte[1024];
while((len=bis.read(arr))!= -1){
bos.write(arr,0,len);
bos.flush();
}
bos.close();
JsonParser parse = new JsonParser();
return (JsonObject)parse.parse(bos.toString(“utf-8”));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
3、在主方法中的测试

public static void main(String args [] ) {
    JsonObject res = null;
    res = getPath("https://jiaotong.baidu.com/trafficindex/city/roadrank?cityCode=307&roadtype=0");
    //res = postJson("https://jiaotong.baidu.com/trafficindex/city/roadrank?cityCode=307&roadtype=0","ip=63.223.108.42");
   /System.out.println(res);
    
    JsonObject jObject = (JsonObject) res.get("data");
    //System.out.println(res.get("data"));
    JsonArray array = jObject.get("list").getAsJsonArray();
     for (int i = 0; i < array.size(); i++) {
   JsonObject sObject = array.get(i).getAsJsonObject();
   System.out.println("id:"+ sObject.get("id").getAsString());
 }
}

你可能感兴趣的:(数据解析)