ホームページ 类库下载 java类库 Java は応答内の XML を解析します

Java は応答内の XML を解析します

Oct 09, 2016 am 09:50 AM

package org.main;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class Demo {
     
    public static GZIPInputStream getReponse(String _url) throws ClientProtocolException, IOException    
    {    
       
        DefaultHttpClient httpclient = new DefaultHttpClient();    
        HttpGet httpget = new HttpGet(_url);    
        HttpResponse response = httpclient.execute(httpget);    
        HttpEntity entity = response.getEntity();       
            InputStream inputs=entity.getContent();      
            GZIPInputStream in = new GZIPInputStream(inputs);
        return in;    
    }    
     
     
 @SuppressWarnings("rawtypes")
public static void main(String[] args) throws Exception {
        
        Map<String, String> map = new HashMap<String, String>();
        SAXReader reader = new SAXReader();
        Document document = reader.read(getReponse("http://wthrcdn.etouch.cn/WeatherApi?city=%E9%95%BF%E6%98%A5"));
        // 得到xml根元素
        Element root = document.getRootElement();
        // 得到根元素的所有子节点
        List<Element> elementList = root.elements();
         
     
        Iterator forecast =  root.elementIterator("forecast");
          if (forecast.hasNext()) {
             Element recordEless = (Element) forecast.next();
             Iterator weather =  recordEless.elementIterator("weather");
                 Element weatherNode = (Element) weather.next();
                 System.out.println();
                 System.out.println("date" + ":" + weatherNode.elementTextTrim("date"));
                 System.out.println("high" + ":" + weatherNode.elementTextTrim("high"));
                 System.out.println("low" + ":" + weatherNode.elementTextTrim("low"));
                 Iterator weatherNodeChild =  weatherNode.elementIterator("day");
                 Element dayNode = (Element) weatherNodeChild.next();
                 System.out.println();
                 System.out.println("type" + ":" + dayNode.elementTextTrim("type"));
                 System.out.println("fengxiang" + ":" + dayNode.elementTextTrim("fengxiang"));
                 System.out.println("fengli" + ":" + dayNode.elementTextTrim("fengli"));
         }      
           
          Iterator zhishus =  root.elementIterator("zhishus");
           while(zhishus.hasNext()) {
                 Element zhishusNode = (Element) zhishus.next();
                 Iterator zhishu =  zhishusNode.elementIterator("zhishu");
                 while(zhishu.hasNext()) {
                      Element zhishuNode = (Element) zhishu.next();
                     System.out.println();
                     System.out.println("name" + ":" + zhishuNode.elementTextTrim("name"));
                     System.out.println("value" + ":" + zhishuNode.elementTextTrim("value"));
                     System.out.println("detail" + ":" + zhishuNode.elementTextTrim("detail"));
                 }        
             }      
                   
 }
}
ログイン後にコピー

最近、パブリック プラットフォーム用の天気クエリ関数を構築しました。原理は、インターフェイスからデータを取得してユーザーに返すことです。ここで使用されるインターフェイスは、xml 型のデータを返します。したがって、dom4j を使用して解析します。


私はもともと Document document = Reader.read();

を使用することを考えていました。その後、そのパラメータは入力ストリームなので、get によって要求された応答をストリームに変換する方法を考え、関連するいくつかのチェックも行いましたオンラインの情報を見て、それは少しばかげていることがわかりました、、、自分でやってください... まず、

      HttpGet httpget = new HttpGet(_url);    
        HttpResponse response = httpclient.execute(httpget);    
        HttpEntity entity = response.getEntity();       
            InputStream inputs=entity.getContent();
ログイン後にコピー

から応答ストリームを取得し、それをreader.read()メソッドに直接渡します。コーディングエラーとして報告されました。 。 。ブラウザから直接アクセスするのは UTF-8 エンコードなので、何だ、と戸惑いました。 。 。

その後、entity.getContentEncoding() を使用して印刷したところ、返されるストリームが gzip でエンコードされていることがわかりました...り...


それを解凍するには、Java に付属の解凍機能を使用するだけです...

GZIPInputStream in = new GZIPInputStream(inputs);
ログイン後にコピー

この記事は「TheAuroraSec」ブログからのものです。このソースは必ず保管しておいてください http://aurorasec.blog.51cto.com/9752323/1859599

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)