Error when simulating cURL using a REST call in java

Currently I am able to run the following command in curl which returns the json response as expected. Note that the input JSON is sent by name “json” in the request as a form parameter. The API will accept only JSON requests and will only support POST method calls.

Request

curl --data 'json={ "startdate": "2012-10-10", "enddate":"2012-10-11" }' http://xxxxx.xxxx.xxx/xxxx/xxxx/xxxx/xxxx

Response

{"startdate":"2012-10-10","status":"true","Api Name":"xxxx","output":{"ROW":"49","EU":"54","NA":"33"},"enddate":"2012-10-11"}

I am simulating the above cURL command using a REST call in java.

The code is shown below

String urlString = "http://xxxxx.xxxx.xxx/xxxx/xxxx/xxxx/xxxx";
URL myUrl = new URL(urlString);
URLConnection urlConn = myUrl.openConnection();

String myData = "json={ "startdate": "2012-10-10", "enddate":"2012-10-11" }" ;
urlConn.setRequestProperty("data", myData);

urlConn.connect();

BufferedReader in = new BufferedReader(newInputStreamReader(urlConn.getInputStream()));

String inputLine;

while ((inputLine = in.readLine()) != null) {
    System.out.println(inputLine);
}
in.close();

But the above code returns the following error.

The stack trace is shown below.

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 405 for URL: http://xxxxx.xxxx.xxx/xxxx/xxxx/xxxx/xxxx
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1615)
    at dashboard.access.data.RAccess.main(RAccess.java:39)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

Answer

Maybe:

urlConn.setRequestMethod("POST");

after openConnection() will fix it? You said your api only allow post requests. And you get a 405 method not allowed.

If not, you can try this link, check out the sendPost() method in first Java HttpURLConnection example chapter: http://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/

Leave a Reply

Your email address will not be published. Required fields are marked *