Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Sunday, January 31, 2016

FileNotFoundException while getting the InputStream object from HttpURLConnection

FileNotFoundException while getting the InputStream object from HttpURLConnection


I am trying to send a post request to a url using HttpURLConnection (for using cUrl in java). The content of the request is xml and at the end point, the application processes the xml and stores a record to the database and then sends back a response in form of xml string. The app is hosted on apache-tomcat locally.

When I execute this code from the terminal, a row gets added to the db as expected. But an exception is thrown as follows while getting the 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();          }      }    }  

Its confusing because the exception is traced to the line InputStream response = con.getInputStream(); and there doesn't seem to be any file involved for a FileNotFoundException.

When I try to open a connection to an xml file directly, it doesn't throw this exception.

The service app uses spring framework and Jaxb2Marshaller to create the response xml.

The class ReadWriteTextFile is taken from here

Thanks.

Edit: Well it saves the data in the DB and sends back a 404 response status code at the same time.

I also tried doing a curl using php and print out the CURLINFO_HTTP_CODE which turns out to be 200.

Any ideas on how do I go about debugging this ? Both service and client are on the local server.

Resolved: I could solve the problem after referring to an answer on SO itself.

It seems HttpURLConnection always returns 404 response when connecting to a url with a non standard port.

Adding these lines solved it

con.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");  con.setRequestProperty("Accept","*/*");  

Answer by tofarr for FileNotFoundException while getting the InputStream object from HttpURLConnection


FileNotFound in this case means you got a 404 from your server - could it be that the server does not like "POST" requests?

Answer by Jon Skeet for FileNotFoundException while getting the InputStream object from HttpURLConnection


FileNotFound is just an unfortunate exception used to indicate that the web server returned a 404.

Answer by BalusC for FileNotFoundException while getting the InputStream object from HttpURLConnection


I don't know about your Spring/JAXB combination, but the average REST webservice won't return a response body on POST/PUT, just a response status. You'd like to determine it instead of the body.

Replace

InputStream response = con.getInputStream();  

by

int status = con.getResponseCode();  

All available status codes and their meaning are available in the HTTP spec, as linked before. The webservice itself should also come along with some documentation which overviews all status codes supported by the webservice and their special meaning, if any.

If the status starts with 4nn or 5nn, you'd like to use getErrorStream() instead to read the response body which may contain the error details.

InputStream error = con.getErrorStream();  

Answer by zero0cool for FileNotFoundException while getting the InputStream object from HttpURLConnection


For anybody else stumbling over this, the same happened to me while trying to send a SOAP request header to a SOAP service. The issue was a wrong order in the code, I requested the input stream first before sending the XML body. In the code snipped below, the line InputStream in = conn.getInputStream(); came immediately after ByteArrayOutputStream out = new ByteArrayOutputStream(); which is the incorrect order of things.

ByteArrayOutputStream out = new ByteArrayOutputStream();  // send SOAP request as part of HTTP body   byte[] data = request.getHttpBody().getBytes("UTF-8");  conn.getOutputStream().write(data);     if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {    Log.d(TAG, "http response code is " + conn.getResponseCode());    return null;  }    InputStream in = conn.getInputStream();  

FileNotFound in this case was an unfortunate way to encode HTTP response code 400.

Answer by Chowza for FileNotFoundException while getting the InputStream object from HttpURLConnection


To anyone with this problem in the future, the reason is because the status code was a 404 (or in my case was a 500). It appears the InpuStream function will throw an error when the status code is not 200.

In my case I control my own server and was returning a 500 status code to indicate an error occurred. Despite me also sending a body with a string message detailing the error, the inputstream threw an error regardless of the body being completely readable.

If you control your server I suppose this can be handled by sending yourself a 200 status code and then handling whatever the string error response was.

Answer by Phuoc Huynh for FileNotFoundException while getting the InputStream object from HttpURLConnection


Please change

con = (HttpURLConnection) new URL("http://localhost:8080/myapp/service/generate").openConnection();  

To

con = (HttpURLConnection) new URL("http://YOUR_IP:8080/myapp/service/generate").openConnection();  


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.