2015-07-21 97 views
1

當我在Web應用程序上執行特定操作時,它會執行ajax調用或沿着該行返回XML格式的某些數據。當我單擊瀏覽器中的Inspect元素並單擊網絡選項卡時,我可以看到請求的XML響應數據。請參閱:enter image description here如何從java http請求中讀取XML?

我試圖在java中執行一個http請求來檢索此XML數據。這裏是java代碼:

private StringBuffer sendGet() { 

    final String USER_AGENT = "Mozilla/5.0"; 
    final String CONTENT_LENGTH = "131"; 
    StringBuffer response = new StringBuffer(); 
    String url = "https://same as the request header"; 

    try { 
     //create the http connection 
     URL obj = new URL(url); 
     HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); 

     con.setRequestMethod("GET"); 
     con.setRequestProperty("User-Agent",USER_AGENT); 
     con.setRequestProperty("Content-Length",CONTENT_LENGTH); 

     int responseCode = con.getResponseCode(); 
     System.out.println("Sending 'GET' request to URL " + url); 
     System.out.println("Response Code:" + responseCode); 

     //read in the get reponse 
     BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); 
     String inputLine; 

     while((inputLine = in.readLine()) != null) { 
      response.append(inputLine.toString()); 
     } 

     //close input stream 
     in.close(); 

     System.out.println("response is: " + response); 

    } catch (MalformedURLException e) { 
     e.printStackTrace(); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    return response; 
} 

對於我創建一個http請求的URL,我在ajax調用頭中使用完全相同的請求URL。請參閱:enter image description here

當我執行GET請求時,我收到了一個200的響應代碼,我認爲請求已成功,但在我的日誌中,儘管我試圖將其打印出來,但它並未顯示XML。日誌顯示如下:

Sending 'GET' request to URL https:"blah blah blah" 
Response Code:200 
response is: 

我還應該注意到,當我嘗試直接在瀏覽器上訪問請求URL時,它只是一個空白的白頁。

當我使用包含網頁的請求URL時,http請求返回DOM中的所有html和js。但是,我試圖使用的請求URL僅僅是一個空白頁面,即使有些XML數據存在懸而未決的情況,我也會迴應一個空白的迴應。我究竟做錯了什麼?爲什麼我無法檢索和顯示XML?在顯示XML之前是否需要解析XML?

+0

我在網絡選項卡中看不到任何https呼叫。所有的呼叫都是通過http端點進行的。你能指出你想要連接的確切URL嗎? – Sourabh

+0

@Sourabh我不完全明白你的問題。本質上,我只是嘗試使用網絡選項卡中提供的請求URL來發出HTTP請求。響應選項卡包含我想要檢索的XML數據,但它好像正在檢索空白,即使http請求返回200響應代碼。我應該使用請求URL嗎? – simhuang

+0

是啊,img不適合我。我懷疑你的問題在於你使用錯誤的方法發送請求,在你的其他問題中進行討論。 POST和GET不一樣,通常會有不同的結果。 –

回答

1

利用DocumentBuilder: -

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
DocumentBuilder db = dbf.newDocumentBuilder(); 
Document doc = db.parse(new URL(url).openStream()); 

對於打印XML: -

DOMSource domSource = new DOMSource(doc); 
StringWriter writer = new StringWriter(); 
StreamResult result = new StreamResult(writer); 
TransformerFactory tf = TransformerFactory.newInstance(); 
Transformer transformer = tf.newTransformer(); 
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //pretty printing 
transformer.transform(domSource, result); 
System.out.println("XML IN String format is: \n" + writer.toString()); 
+0

是不能讀取XML的bufferreader?這是爲什麼它返回空白? – simhuang

+0

@mrtofu不,我不這麼認爲,只是提供瞭解決方案,如果你想玩XML,解析或遍歷它,使用'DocumentBuilder' –

2

我,改成一個POST請求(相同的瀏覽器做了什麼),解決了這個問題。我還包括與該請求相關聯的表單數據,如上圖中所示。

private StringBuffer sendPost() { 

    StringBuffer response = new StringBuffer(); 
    String url = "https://example.com/snowbound/AjaxServlet"; 
    final String CONTENT_LENGTH = "131"; 
    final String CONTENT_TYPE = "application/x-www-form-urlencoded"; 
    final String ACCEPT_LANGUAGE = "en-US,en;q=0.8"; 

    try { 
     //create http connection 
     URL obj = new URL(url); 
     HttpsURLConnection connection = (HttpsURLConnection) obj.openConnection(); 

     //add request header 
     connection.setRequestMethod("POST"); 
     connection.setDoInput(true); 
     connection.setDoOutput(true); 
     connection.setUseCaches(false); 
     connection.setRequestProperty("Accept-Language", ACCEPT_LANGUAGE); 
     connection.setRequestProperty("Content-Type", CONTENT_TYPE); 
     connection.setRequestProperty("Content-Length", CONTENT_LENGTH); 

     DataOutputStream output = new DataOutputStream(connection.getOutputStream()); 

     //form data 
     String content = "documentId=3896&action=getAnnotationModel&annotationLayer=1&pageCount=1&pageIndex=0"; 

     //write output stream and close output stream 
     output.writeBytes(content); 
     output.flush(); 
     output.close(); 

     //read in the response data 
     BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
     String inputLine; 
     while((inputLine = input.readLine()) != null) { 
      response.append(inputLine.toString()); 
     } 

     //close input stream 
     input.close(); 

     //print out content 
     int responseCode = connection.getResponseCode(); 
     System.out.println("response code: " + responseCode); 
     System.out.println("respone is: " + response); 

    } catch (MalformedURLException e) { 
     e.printStackTrace(); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    return response; 
}