HttpUrlConnection:如何将XML响应转换为字符串? [英] HttpUrlConnection: how to get the XML response into a String?

查看:142
本文介绍了HttpUrlConnection:如何将XML响应转换为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 HttpURLConnection 发布到REST API。我仍然没有成功发布任何东西,所以我试图找回应该来自API的XML响应。



下面是我放在一起的代码段,它给我提出了一些问题:

  //处理响应 - 需要返回XML响应。 
InputStream stream = connection.getInputStream();
connection.disconnect();

BufferedReader br = new BufferedReader(stream);
字符串结果;
字符串行; ((line = br.readLine())!= null){
System.out.println(line);
while
结果+ =行;
}
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;
导入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 {
$ b @Override
public String postToRemoteServer(String serviceUrl)throws HelpDeskTestException {
尝试{
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 /请求者%3E%3Csubject%3ETest%3C /受试者%3E%3Cdescription%3ETesting%20curl%20input%20again%3C /描述%3E%3C /细节%3E%3C /操作%3E; //将参数放在这里进行测试。

//尝试使用HttpURLConnection而不是普通的URLConnection

URL url =新的URL(serverPath);
HttpURLConnection连接=(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();

//进程响应 - 需要返回XML响应。
InputStream stream = connection.getInputStream();
connection.disconnect();

//将输出流转换为字符串
BufferedReader br = new BufferedReader(stream);
字符串结果;
字符串行; ((line = br.readLine())!= null){
System.out.println(line);
while
结果+ =行;
}
br.close();

System.out.println(result);
返回结果;
}
catch(final Exception e){
System.out.println(e.getMessage());
抛出新的HelpDeskTestException();




解决方案

我有两个意见。
$ b


  1. 移动 connection.disconnect(); 到最后,你完成了阅读,即在 br.close(); 行之后


  2.   InputStream stream = connection.getInputStream(); 
    InputStreamReader isReader = new InputStreamReader(stream);

    //将输出流放入字符串
    BufferedReader br = new BufferedReader(isReader);


希望有效!


I am using HttpURLConnection to post to a REST API. I still have not successfully posted anything, so I'm trying to get back the XML response that should be coming from the API.

Here is the segment of the code that I've put together that is giving me the issues:

// 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();

The compiler is not happy with this line (the suggested fix is "Change type of stream to reader"):

BufferedReader br = new BufferedReader(stream);

Does anyone have any suggestions as to how I might do this properly? Any help appreciated.

Complete code here:

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

解决方案

I have two observations.

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

Hope that works!

这篇关于HttpUrlConnection:如何将XML响应转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆