如何从HttpURLConnection POST获得响应

时间:2019-07-19 17:27:48

标签: java

我正在尝试将POST(主体中包含XML)发送到API,并获得返回的XML响应。我需要从响应正文(从ERROR元素中)获得确认或错误的详细信息。

我可以发送POST,它确实触发了API中的更改,但是我无法读取响应。

当我从邮递员手动发送POST时,我触发了API中的更改,并且我可以看到来自API的响应为text/html;charset=charset=utf-8

这是我当前的代码:

      URL url = new URL(urlString);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);

        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

        writer.write(xmlString);
        writer.flush();
        String line;
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        writer.close();
        reader.close();

响应正文应采用以下格式:

<Root>
    <Session>
        <UserId>theUserID</UserId>
        <Password>thePassword</Password>
        <ERROR Status="0" Description="Logon Successful" />
    </Session>
    <ActivityList>
        <Activity Type="ReqUp" Incident="12345" ElapsedTime="350" 
      Description="example response" 
      Status="Complete">
            <ERROR Status="0" Description="OK" />
        </Activity>
    </ActivityList>
</Root>

当前/实际结果:
line显示为null

2 个答案:

答案 0 :(得分:2)

由于您希望xml从服务器返回,因此可能需要在请求中添加“ accept”标头,以告诉服务器您(客户端)将“接受” xml。从您的帖子中看来,默认值为html。

这可能对您有用:

  URL url = new URL(urlString);

  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  conn.setRequestProperty("accept", "application/xml");
  conn.setDoOutput(true);

  OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

如果要将xml发送到服务器,则可能还需要添加“内容类型”标头,如下所示:

  conn.setRequestProperty("content-type", "application/xml");

ref:https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html

答案 1 :(得分:0)

我的原始代码中存在一个错误,该错误阻止行形成null以外的任何形式。

正确的代码如下:

        URL url = new URL(urlString);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("accept", "text/html");


        conn.setDoOutput(true);

        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

        writer.write(xmlString);
        writer.flush();
        String builtResponse = "";
        String line ="";
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = reader.readLine()) != null) {
            builtResponse += line;
        }
        writer.close();
        reader.close();