HttpUrlConnection:如何将XML响应转换为字符串?

4
我将使用HttpURLConnection来向REST API发送POST请求。目前还没有成功地发送过任何数据,因此我试图获取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();

编译器对此行不满意(建议更改为“将流的类型更改为reader”):
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();
        }
    }
}
3个回答

6
我有两个观察结果。
  1. Move connection.disconnect(); towards the end, where you are done with reading i.e. after the br.close(); line.

  2. Follow Below sequence:

    InputStream stream = connection.getInputStream();
    InputStreamReader isReader = new InputStreamReader(stream ); 
    
    //put output stream into a string
    BufferedReader br = new BufferedReader(isReader );
    
希望这能够起作用!

1

BufferedReader不直接接受输入流,它只接受reader对象。将输入流包装在InputStreamReader中,并将其传递给BufferedReader。

BufferedReader br = new BufferedReader(new InputStreamReader(stream));


0

- 看看这个方法,它来自我的工作项目。

- 我以xml格式发送请求,并以xml格式接收数据,并将其转换为字符串

public String postData(String url, String xmlQuery) {



        final String urlStr = url;
        final String xmlStr = xmlQuery;
        final StringBuilder sb  = new StringBuilder();


        Thread t1 = new Thread(new Runnable() {

            public void run() {

                HttpClient httpclient = DefaultHttpClient();

                HttpPost httppost = new HttpPost(urlStr);


                try {

                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                            1);
                    nameValuePairs.add(new BasicNameValuePair("xml", xmlStr));

                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    HttpResponse response = httpclient.execute(httppost);

                    Log.d("Vivek", response.toString());

                    HttpEntity entity = response.getEntity();
                    InputStream i = entity.getContent();

                    Log.d("Vivek", i.toString());
                    InputStreamReader isr = new InputStreamReader(i);

                    BufferedReader br = new BufferedReader(isr);

                    String s = null;


                    while ((s = br.readLine()) != null) {

                        Log.d("YumZing", s);
                        sb.append(s);
                    }


                    Log.d("Check Now",sb+"");




                } catch (ClientProtocolException e) {

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

        });

        t1.start();
        try {
            t1.join();
        } catch (InterruptedException e) {

            e.printStackTrace();
        }


        System.out.println("Getting from Post Data Method "+sb.toString());

        return sb.toString();
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接