java - HttpUrlConnection : how to get the XML response into a String?

标签 java rest gwt

我正在使用 HttpURLConnection 发布到 REST API。我仍然没有成功发布任何内容,所以我试图取回应该来自 API 的 XML 响应。

这是我放在一起的代码段,它给我带来了问题:

// Process response - need to get XML response back.
InputStream stream = connection.getInputStream();
connection.disconnect();

BufferedReader br = new BufferedReader(stream);
String result;
String line;
while ((line = br.readLine()) != null) {
    System.out.println(line);
    result += line;
}
br.close();

编译器对这一行不满意(建议的修复是“将流类型更改为读取器”):

BufferedReader br = new BufferedReader(stream);

有人对我如何正确执行此操作有任何建议吗? 任何帮助表示赞赏。

完整代码在这里:

package com.gwt.HelpDeskTest.server;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.gwt.HelpDeskTest.client.HelpDeskTestService;
import com.gwt.HelpDeskTest.shared.HelpDeskTestException;

@SuppressWarnings("serial")
public class HelpDeskTestImpl extends RemoteServiceServlet implements HelpDeskTestService {

    @Override
    public String postToRemoteServer(String serviceUrl) throws HelpDeskTestException {
        try {
            final String serverPath= "http://helpdesk.rmi.org/sdpapi/request/";     
            final String serverParameters = "OPERATION_NAME=ADD_REQUEST&TECHNICIAN_KEY=D4ADD3A3-9CD4-4307-932B-29E96BCFA5B6&INPUT_DATA=%3C?xml%20version=%25221.0%2522%20encoding=%2522utf-8%2522?%3E%3COperation%3E%3CDetails%3E%3Crequester%3EBetsy%20Leach%3C/requester%3E%3Csubject%3ETest%3C/subject%3E%3Cdescription%3ETesting%20curl%20input%20again%3C/description%3E%3C/Details%3E%3C/Operation%3E"; // Put parameters here for testing.

            // trying HttpURLConnection instead of a plain URLConnection

            URL url = new URL(serverPath); 
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();           
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setInstanceFollowRedirects(false); 
            connection.setRequestMethod("POST"); 
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
            connection.setRequestProperty("charset", "utf-8");
            connection.setRequestProperty("Content-Length", "" + Integer.toString(serverParameters.getBytes().length));
            connection.setUseCaches (false);

            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.writeBytes(serverParameters);
            wr.flush();
            wr.close();

            // Process response - need to get XML response back.
            InputStream stream = connection.getInputStream();
            connection.disconnect();

            // Put output stream into a String
            BufferedReader br = new BufferedReader(stream);
            String result;
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
                result += line;
            }
            br.close();

            System.out.println(result);
            return result;
        } 
        catch (final Exception e) {
            System.out.println(e.getMessage());
            throw new HelpDeskTestException();
        }
    }
}

最佳答案

我有两个观察结果。

  1. 移动connection.disconnect();最后,您完成阅读的地方,即在 br.close(); 之后行。

  2. 遵循以下顺序:

    InputStream stream = connection.getInputStream();
    InputStreamReader isReader = new InputStreamReader(stream ); 
    
    //put output stream into a string
    BufferedReader br = new BufferedReader(isReader );
    

希望有用!

关于java - HttpUrlConnection : how to get the XML response into a String?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12805107/

相关文章:

java - 尝试为 JPA 表添加新值时出错

java - Apache Camel 和 CXF : How do i send HTTP status code from bean

node.js - 在使用 nodejs 和 express 制作的 REST API 中设置响应状态和 JSON 内容的正确方法

java - GWT 和 GWTP 之间的区别

java - 正则表达式在双引号上分割字符串仅保留引号之间的内容

java - 在 Debug View 中,程序终止后,切换回 Eclipse 中的 Java View

json - 如何使用 replaceAll 方法删除 JSON 数组、括号、键和值?

javascript - JsInterop 包装一个 javascript 函数属性

java - 如果有对服务器的异步调用,如何在 UI 初始化结束时显示 GWT 对话框?

java - 使用 Apache POI 重新计算电子表格中的公式