Webservice call returns error 500
Asked Answered
C

5

8

I have started a small project in Java.
I have to create a client which will send xml to a url as a HTTP POST request.
I try it using java.net.* package (Following is the piece of code) but I am getting error as follows:

java.io.IOException: Server returned HTTP response code: 500 for URL: "target url"
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
    at newExample.main(newExample.java:36)

My code is as follows:

try {
        URL url = new URL("target url");

        URLConnection connection = url.openConnection();

        if( connection instanceof HttpURLConnection )
            ((HttpURLConnection)connection).setRequestMethod("POST");

        connection.setRequestProperty("Content-Length", Integer.toString(requestXml.length()) );
        connection.setRequestProperty("Content-Type","text/xml; charset:ISO-8859-1;");
        connection.setDoOutput(true);
        connection.connect();           

        // Create a writer to the url
        PrintWriter writer = new PrintWriter(new
        OutputStreamWriter(connection.getOutputStream()));

        // Get a reader from the url
        BufferedReader reader = new BufferedReader(new
        InputStreamReader(connection.getInputStream()));

        writer.println();
        writer.println(requestXml);
        writer.println();
        writer.flush();

        String line = reader.readLine();
            while( line != null ) {
                    System.out.println( line );
                    line = reader.readLine();
            }


    } catch (MalformedURLException e) {
                    e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Please help with suitable examples or any other ways of doing this.

Point errors/mistakes in above code or other possibilities.

My Web Service is in spring framework

xml to send is in the string format: requestXml

Cocytus answered 1/3, 2011 at 8:8 Comment(3)
HTTP error 500 is "internal server error" a generic error returned when the service encounters an error, or throws an exception. You might want to read the full response body and see if has any further informationBrew
error code 500 is an Internal Server Error. So I'd concentrate on the server rather than the client really.Warsle
If your URL is correct (can check from browser), there is not much that you can do. Looks like server side error.Pivoting
A
22

The problem lies in below code

// Get a reader from the url
BufferedReader reader = new BufferedReader(new
InputStreamReader(connection.getInputStream()));

As the service might not always return you the proper response... as you are calling a service through http, it can be possible that the server itself is not available or the service is not available. So you should always check for the response code before reading response from streams, based on the response code you've to decide whether to read it from inputStream for success response or from errorStream for failure or exception condition.

BufferedReader reader = null;

if(connection.getResponseCode() == 200)
{
reader = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
}
else
{
reader = new BufferedReader(new
InputStreamReader(connection.getErrorStream()));
}

This would resolve the problem

Atonal answered 21/10, 2012 at 20:38 Comment(2)
getResponeCode, does this method actually exists? I dont find it here - docs.oracle.com/javase/7/docs/api/java/net/URLConnection.htmlConstrue
I typecasted connection object to HttpURLConnection then I could get response code.Construe
P
3

The problem is inside your server code or the server configuration:

10.5.1 500 Internal Server Error

The server encountered an unexpected condition which prevented it from fulfilling the request.

(w3c.org/Protocols)

If the server is under your control (should be, if I look at the URL [before the edit]), then have a look at the server logs.

Pandemic answered 1/3, 2011 at 8:14 Comment(0)
M
1

Well, you should close your streams and connections. Automatic resource maangement from Java 7 or http://projectlombok.org/ can help. However, this is probably not the main problem.

The main problem is that the server-side fails. HTTP code 500 means server-side error. I can't tell you the reason, because I don't know the server side part. Maybe you should look at the log of the server.

Mcalpin answered 1/3, 2011 at 8:14 Comment(0)
M
1

I think that your problem is that you are opening the input stream before you have written and closed the output stream. Certainly, the Sun Tutorial does it that way.

If you open the input stream too soon, it is possible that the output stream will be closed automatically, causing the server to see an empty POST request. This could be sufficient to cause it to get confused and send a 500 response.

Even if this is not what is causing the 500 errors, it is a good idea to do things in the order set out in the tutorial. For a start, if you accidentally read the response before you've finished writing the request, you are likely to (at least temporarily) lock up the connection. (In fact, it looks like your code is doing this because you are not closing the writer before reading from the reader.)

A separate issue is that your code does not close the connection in all circumstances, and is therefore liable to leak network connections. If it does this repeatedly, it is likely to lead to more IOExceptions.

Massicot answered 1/3, 2011 at 9:33 Comment(0)
F
0

If you are calling an External Webservice and passing a JSON in the REST call, check the datatype of the values passed.

Example:

{ "originalReference":"8535064088443985",
  "modificationAmount":
    { "amount":"16.0",
      "currency":"AUD"
    },
  "reference":"20170928113425183949",
  "merchantAccount":"MOM1"
}

In this example, the value of amount was sent as a string and the webservice call failed with Server returned HTTP response code: 500. But when the amount: 16.0 was sent, i.e an Integer was passed, the call went through. Though you have referred API documentation while calling such external APIs, small details like this could be missed.

Faubion answered 29/9, 2017 at 11:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.