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

时间:2015-07-21 18:02:42

标签: java xml http

当我在网络应用上执行某项操作时,它会执行ajax调用或沿该行返回XML格式的某些数据。当我单击浏览器中的On Inspect元素并单击网络选项卡时,我可以看到所请求的XML响应数据。见:enter image description here

我尝试在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时,http请求会返回DOM中的所有html和js。但是我试图使用的请求URL只是一个空白页面,即使有一些xml数据,也会给我一个空白的回复。我究竟做错了什么?为什么我无法检索和显示XML?在显示XML之前是否需要解析XML?

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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());