JAVA 通過jsonpath解析懂車帝詳情頁介面

weixin_34253539發表於2018-12-28

配置Maven

        <!--jsonpath maven-->
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <version>2.4.0</version>
        </dependency>

懂車帝文章介面:

http://m.dcdapp.com/motor/m/article/detail?group_id=6631042760742797827

話不多說,直接上程式碼

import com.jayway.jsonpath.JsonPath;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

public class JsonpathUtil {


    public static String readData() throws Exception {
        String json = "";
        //url中不可以出現空格,空格全部用%20替換
        String url = "http://m.dcdapp.com/motor/m/article/detail?group_id=6631042760742797827";
        URL urls = new URL(url);
        java.net.HttpURLConnection conn = (java.net.HttpURLConnection)urls.openConnection();
        //因為伺服器的安全設定不接受Java程式作為客戶端訪問,解決方案是設定客戶端的User Agent
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        //只可以設定為GET方式,不可以使用POST方式
        //conn.setRequestMethod("POST");
        conn.setRequestMethod("GET");
        //設定編碼格式為UTF-8
        conn.setRequestProperty("contentType", "UTF-8");

        //得到輸入流
        InputStream inputStream = conn.getInputStream();
        //從輸入流中獲取資料(一定要設定編碼格式,不然在伺服器端接收到的資料可能亂碼)
        BufferedReader bf=new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));

        String line = null;
        while((line=bf.readLine())!=null){//一行一行的讀
            json = json + line;
        }
        return json;

    }


    public static void jsonutil(){
        try {
            String html =  readData();
            String publish_time = JsonPath.read(html, "$.data.publish_time").toString();
            String title = JsonPath.read(html, "$.data.title").toString();
            String content = JsonPath.read(html, "$.data.content").toString();
            String source = JsonPath.read(html, "$.data.source").toString();
            System.out.println( publish_time );
            System.out.println( source );
            System.out.println( title );
            System.out.println( content );
        } catch (Exception e) {

            System.out.println( e );
        }
    }

    public static void main(String[] args) {
        jsonutil();
    }
}

解析結果:


6591571-95b66f7200171094.png
image.png

相關文章