2

When I contact a web service using a Java HttpUrlConnection it just returns a 400 Bad Request (IOException). How do I get the XML information that the server is returning; it does not appear to be in the getErrorStream of the connection nor is it in any of the exception information.

When I run the following PHP code against a web service:

<?php

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://www.myclientaddress.com/here/" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST,1 );
curl_setopt($ch, CURLOPT_POSTFIELDS,"username=ted&password=scheckler&type=consumer&id=123456789&zip=12345");

$result=curl_exec ($ch);
echo $result;
?>

it returns the following:

<?xml version="1.0" encoding="utf-8"?>
<response>
    <status>failure</status>
    <errors>
        <error name="RES_ZIP">Zip code is not valid.</error>
        <error name="ZIP">Invalid zip code for residence address.</error>
    </errors>
</response>

so I know the information exists

threadhack
  • 127
  • 4
  • 6

3 Answers3

7

HttpUrlConnection returns FileNotFoundException if you try to read the getInputStream() from the connection, so you should instead use getErrorStream() whenever the status code is equal or higher than 400.

More than this, please be careful since it's not only 200 to be the success status code, even 201, 204, etc. are often used as success statuses.

Here is an example of how I went to manage it

// ... connection code code code ...

// Get the response code 
int statusCode = connection.getResponseCode();

InputStream is = null;

if (statusCode >= 200 && statusCode < 400) {
   // Create an InputStream in order to extract the response object
   is = connection.getInputStream();
}
else {
   is = connection.getErrorStream();
}

// ... callback/response to your handler....

In this way, you'll be able to get the needed response in both success and error cases.

Hope this helps!

gpiazzese
  • 445
  • 7
  • 9
0

I had same issue and adding below two lines resolved it.

httpConn.setRequestProperty("Connection", "Close"); System.setProperty("http.keepAlive", "false");

Akshay
  • 657
  • 2
  • 19
  • 38
0

If the server is returning XML and you pass the parameters as a url, why not just use a library that supports JAX-RS (Java's REST webservices API), such as Apache CXF?

I know it supports JAX-RS because it has a chapter in the manual.

Powerlord
  • 87,612
  • 17
  • 125
  • 175
  • I was not involved in the system design so I can't answer that. It also depends on the client, some return XML some return text. Regardless of that, doesn't the connection support just capturing the raw return? – threadhack Jun 14 '10 at 15:24