简体   繁体   English

如何从XML http请求中读取XML?

[英]How do I read in the XML for from java http request?

When I perform a certain action on a web app, it performs a ajax call or something along that line that returns some data in XML format. 当我在Web应用程序上执行某个操作时,它会执行ajax调用或沿该行返回XML格式的某些数据。 When I click On Inspect element in the browser and click on the networks tab, I can see the XML response data that was requested. 当我单击浏览器中的On Inspect元素并单击网络选项卡时,我可以看到所请求的XML响应数据。 see: 看到: 在此输入图像描述

I tried to perform a http request in java to retrieve this XML data. 我试图在java中执行http请求以检索此XML数据。 Here is the java code: 这是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;
}

For the URL I am creating a http request, I am using the exact same request URL in the ajax calls header. 对于我正在创建http请求的URL,我在ajax调用头中使用完全相同的请求URL。 see: 看到: 在此输入图像描述

When I perform the GET request, I received a response code of 200 which I assume the request was successful, but on my log it displays no XML even though I try to print it out. 当我执行GET请求时,我收到的响应代码为200,我认为请求成功,但在我的日志中,即使我尝试将其打印出来,它也不会显示XML。 The log displayed this: 日志显示如下:

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

I should also note that when I try to go to the request URL directly on the browser it's just a blank white page. 我还应该注意,当我尝试直接在浏览器上访问请求URL时,它只是一个空白的白页。

When I use a request URL that contains a webpage, the http request returns all the html and js in the DOM. 当我使用包含网页的请求URL时,http请求返回DOM中的所有html和js。 But the request URL I was trying to use which is just a blank page returns a blank response to me even though there are suspose to be some xml data. 但是我试图使用的请求URL只是一个空白页面,即使有一些xml数据,也会给我一个空白的回复。 What am I doing wrong? 我究竟做错了什么? Why is it that I cannot retrieve and display the XML? 为什么我无法检索和显示XML? Do I need to parse the XML before it can be displayed? 在显示XML之前是否需要解析XML?

I solved the issue by changing it to a POST request (same as what the browser did). 我通过将其更改为POST请求(与浏览器的操作相同)解决了该问题。 I also included the form data associated with that request as shown in the pictures up there. 我还包括与该请求相关联的表单数据,如图中所示。

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;
}

Make use of DocumentBuilder :- 使用DocumentBuilder : -

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

For printing XML :- 用于打印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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM