I am using the following sendReuqest() method in the util class in the
integration test base to send a request to an API through the ESB connector
and get the response.
When the *404 Not found *or* 400 Bad request* is returned from the API(
API->ESB connector ->Test connection), the method getResponseCode()in
HttpURLConnection
returns "-1" instead of the http error code.

public static RestResponse sendRequest(String addUrl, String query) throws
IOException {
RestResponse restResponse = new RestResponse();
String charset = "UTF-8";
URLConnection connection = new URL(addUrl).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json;charset=" +
charset);

OutputStream output = null;
try {
output = connection.getOutputStream();
output.write(query.getBytes(charset));
} finally {
if (output != null) {
try {
output.close();
} catch (IOException logOrIgnore) {
log.error("Error while closing the connection");
}
}
}

HttpURLConnection httpConn = (HttpURLConnection) connection;
InputStream response;

if (httpConn.getResponseCode() >= 400) {
response = httpConn.getErrorStream();
} else {
response = connection.getInputStream();
}

String out = "{}";
if (response != null) {
StringBuilder sb = new StringBuilder();
byte[] bytes = new byte[1024];
int len;
while ((len = response.read(bytes)) != -1) {
sb.append(new String(bytes, 0, len));
}

if (!sb.toString().trim().isEmpty()) {
out = sb.toString();
}
}
int resc=httpConn.getResponseCode(); //returns -1
restResponse.setResponseCode(resc);
try {
restResponse.setBody(new JSONObject(out));
} catch (JSONException e) {
log.error(e.getMessage());
}
}

Anything suggestions? Thanks in advance

-- 
Regards,

*Madhawa Bandara*
Software Engineer
WSO2, Inc.
lean.enterprise.middleware

Mobile - *+94777487726 <%2B94777487726>*
Blog* - *classdeffound.blogspot.com
_______________________________________________
Dev mailing list
[email protected]
http://wso2.org/cgi-bin/mailman/listinfo/dev

Reply via email to