I am trying to send a mail request to a URL using HttpURLConnection (for using cUrl in java). The content of the request is xml, and at the endpoint, the application processes the xml and stores the record in the database, and then sends the response as an xml string. The application is hosted locally on apache-tomcat.
When I execute this code from the terminal, the line is added to db, as expected. But the exception is thrown as follows, getting an InputStream from the connection
java.io.FileNotFoundException: http://localhost:8080/myapp/service/generate at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1401) at org.kodeplay.helloworld.HttpCurl.main(HttpCurl.java:30)
Here is the code
public class HttpCurl { public static void main(String [] args) { HttpURLConnection con; try { con = (HttpURLConnection) new URL("http://localhost:8080/myapp/service/generate").openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); con.setDoInput(true); File xmlFile = new File("test.xml"); String xml = ReadWriteTextFile.getContents(xmlFile); con.getOutputStream().write(xml.getBytes("UTF-8")); InputStream response = con.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(response)); for (String line ; (line = reader.readLine()) != null;) { System.out.println(line); } reader.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
This is confusing because the exception is traced to the line InputStream response = con.getInputStream(); , and there seems to be no file to throw a FileNotFoundException.
When I try to open a connection to an xml file directly, it does not throw this exception.
The service application uses the spring framework and Jaxb2Marshaller to create an xml response.
The ReadWriteTextFile class is taken from here.
Thank.
Edit: Well, this saves the data in the database and at the same time sends back a 404 response status code.
I also tried to make curl using php and print out CURLINFO_HTTP_CODE , which would turn out to be 200.
Any ideas on how I can debug this? Both services and the client are on the local server.
Solved: I could solve the problem by contacting the answer to SO itself.
It seems that HttpURLConnection always returns a 404 response when connected to a non-standard port url.
Adding these lines resolved it
con.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) "); con.setRequestProperty("Accept","*/*");