FileNotFoundException on HttpsURLConnection with POST and unmutable doOutput variable - java

I'm trying to POST some data to an https url, in my android application, in order to get a json format response.
I'm facing two problems:
is = conn.getInputStream();
throws
java.io.FileNotFoundException
I don't get if i do something wrong with HttpsURLConnection.
The second problem arose when i debug the code (used eclipse); I set a breakpoint after
conn.setDoOutput(true);
and, when inspecting conn values, I see that the variable doOutput remain set to false and type GET.
My method for https POST is the following, where POSTData is a class extending ArrayList<NameValuePair>
private static String httpsPOST(String urlString, POSTData postData, List<HttpCookie> cookies) {
String result = null;
HttpsURLConnection conn = null;
OutputStream os = null;
InputStream is = null;
try {
URL url = new URL(urlString);
conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setUseCaches (false);
conn.setDoInput(true);
conn.setDoOutput(true);
if(cookies != null)
conn.setRequestProperty("Cookie",
TextUtils.join(";", cookies));
os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(postData.getPostData());
writer.flush();
writer.close();
is = conn.getInputStream();
BufferedReader r = new BufferedReader(
new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
result = total.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
if (conn != null) {
conn.disconnect();
}
}
return result;
}
A little update: apparently eclipse debug lied to me, running and debugging on netbeans shows a POST connection. Error seems to be related to parameters i'm passing to the url.

FileNotFoundException means that the URL you posted to doesn't exist, or couldn't be mapped to a servlet. It is the result of an HTTP 404 status code.
Don't worry about what you see in the debugger if it doesn't agree with how the program behaves. If doOutput really wasn't enabled, you would get an exception obtaining the output stream.

Related

getInputStream freezes and never finishes

Im reading a simple text file from my website using HttpURLConnection, and when it calls getInputStream it freezes and never finishes, the getResponseCode returns 200. It was working at first every time then it stopped working.
I have search for a solution all over the internet and none work. I think it maybe ddos protection on the web server, or something on there end blocking it.
public static String getLatestInfo(String urlString){
URL url = null;
HttpURLConnection connection = null;
/*InputStream inputStream = null;
InputStreamReader isr = null;
BufferedReader in = null;*/
try {
url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
//connection.setRequestMethod("GET");
//connection.setDoOutput(true);
connection.setConnectTimeout(5000); // 5 seconds connectTimeout
connection.setReadTimeout(5000); // 5 seconds socketTimeout
connection.setRequestProperty("Connection", "close");
connection.setRequestProperty("Content-Type", "text/xml");
connection.setRequestProperty("Accept", "text/xml");
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
connection.connect();
if (connection.getResponseCode() == 200) {
try(InputStream inputStream = connection.getInputStream())
{
try(InputStreamReader isr = new InputStreamReader(inputStream, "UTF-8")) {
try(BufferedReader in = new BufferedReader(isr))
{
String line;
String config = "";
while ((line = in.readLine()) != null) {
config = config + line + "\n";
}
return config;
}
}
}
/*inputStream = connection.getInputStream();
isr = new InputStreamReader(inputStream, "UTF-8");
in = new BufferedReader(isr);
String line;
String config = "";
while ((line = in.readLine()) != null) {
config = config + line + "\n";
}
return config;*/
}
}
catch (SocketTimeoutException e)
{
System.out.println("Timeout: " + e.getMessage());
}
catch (MalformedURLException e) {
System.out.println("Malformed URL: " + e.getMessage());
}
catch (IOException e) {
System.out.println("I/O Error: " + e.getMessage());
try {
System.out.println(connection.getResponseCode());
} catch (IOException e1) {
e1.printStackTrace();
}
}
finally {
if (connection != null) connection.disconnect();
/*try {
if (inputStream != null) inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (in != null) in.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (isr != null) isr.close();
} catch (IOException e) {
e.printStackTrace();
}*/
}
return null;}
I started simple and have added all the suggestion that should've fix it.. it gets response code 200 and then freezes on connection.getInputStream()
There were multiple things wrong in my code:
Some streams for file reading wasn't closed.
I was using FileInputStream/FileOutputStream and it was making it freeze. This explains it. Even though it shows a work around, but it still would make it freeze.
The main problem i was using SwingUtilities.invokeLater(new Runnable ()... and it was freeze and random points.
Fixing all the above factors and it solved my problem.

IOException: Server returned 400 error code

Hi Below is the piece of code. In the below code, when i close writer after write, server gives expected results. But if it is closed in finally block it return 400 bad request. Is there any reason for this behavior?
BufferedReader br = null;
HttpURLConnection conn = null;
OutputStreamWriter writer = null;
String ip = "test"
try {
URL url = new URL(http://someurl));
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setConnectTimeout(0);
conn.setRequestProperty("Content-Type", "application/json");
writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
writer.write(ip);
// writer.close();
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
} catch (final Exception e) {
LOG.error("Error" + e);
}
finally
{
//Closing writer in finally block.
if(writer != null)
{
try
{
writer.close();
}
catch (IOException e) {
LOG.error("Error in closing Writer", e);
}
}
if (br != null)
{
try
{
br.close();
}
catch (final IOException e)
{
LOG.error("Error: ", e);
}
}
if(conn != null){
conn.disconnect();
}
}
You need to flush the contents to server. Use writer.flush() instead of writer.close() once you are done with writing request, just before reading response.

Java HttpURLConnection invoke remote server and returned 500 status

I want to invoke remote server using HttpURLConnection, here is my function:
public String invokeAwvsServer(String api, String param, String method){
System.out.println(api+param);
BufferedReader reader = null;
HttpURLConnection connection = null;
OutputStreamWriter out = null;
try {
URL url = new URL(api);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod(method);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("X-Auth", apiKey);
connection.connect();
if(method.equalsIgnoreCase("POST")){
out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
out.append(param);
out.flush();
}
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line;
StringBuffer res = new StringBuffer();
while ((line = reader.readLine()) != null) {
res.append(line);
}
return res.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(connection != null){
connection.disconnect();
}
if(out != null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "error";
}
I use this function in its own class and works well, but if I call it in other class ,the remote server return 500 status code and JVM throws exception like:
java.io.IOException: Server returned HTTP response code: 500 for URL:...
What`s the reason?Thanks a lot:)

How to get the response data from cloud to string

I want to get the response to a string variable from the data from the cloud.
ClientResource cr = new ClientResource("http://localhost:8888/users");
cr.setRequestEntityBuffering(true);
try {
try {
cr.get(MediaType.APPLICATION_JSON).write(System.out);
} catch (IOException e) {
e.printStackTrace();
}
} catch (ResourceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I have response as JSON in the console and I want to convert it to string , Is the GSON library would be helpful? I haven't used it yet .What modifications should I need to do in my codes? Can anybody help me here.
In fact, Restlet receives the response payload as String and you can directly have access to this, as described below:
ClientResource cr = new ClientResource("http://localhost:8888/users");
cr.setRequestEntityBuffering(true);
Representation representation = cr.get(MediaType.APPLICATION_JSON);
String jsonContentAsString = representation.getText();
Hope it helps you,
Thierry
Below is a working example:
try {
URL url = new URL("http://localhost:8888/users");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Raw Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Java, FileNotfound Exception, While reading conn.getInputStream()

Please tell me some one, How to resolve this problem,
Sometime I am getting Filenotfound Exception and Some time this code working fine.
Below is my code,
public String sendSMS(String data, String url1) {
URL url;
String status = "Somthing wrong ";
try {
url = new URL(url1);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
conn.setRequestProperty("Accept","*/*");
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String s;
while ((s = rd.readLine()) != null) {
status = s;
}
rd.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
wr.close();
} catch (MalformedURLException e) {
status = "MalformedURLException Exception in sendSMS";
e.printStackTrace();
} catch (IOException e) {
status = "IO Exception in sendSMS";
e.printStackTrace();
}
return status;
}
Rewrite like this and let me know how you go... (note closing of reading and writing streams, also the cleanup of streams if an exception is thrown).
public String sendSMS(String data, String url1) {
URL url;
OutputStreamWriter wr = null;
BufferedReader rd = null;
String status = "Somthing wrong ";
try {
url = new URL(url1);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
conn.setRequestProperty("Accept","*/*");
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
wr.close();
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String s;
while ((s = rd.readLine()) != null) {
status = s;
}
rd.close();
} catch (Exception e) {
if (wr != null) try { wr.close(); } catch (Exception x) {/*cleanup*/}
if (rd != null) try { rd.close(); } catch (Exception x) {/*cleanup*/}
e.printStackTrace();
}
return status;
}
This issue seems to be known, but for different reasons so its not clear why this happend.
Some threads would recommend closing the OutputStreamWriter as flushing it is not enough, therefor i would try to clos it directly after fushing as you are not using it in the code between the flush and close.
Other threads show that using a different connections like HttpURLConnection are avoiding this problem from occuring (Take a look here)
Another article suggests to use the URLEncoder class’ static method encode. This method takes a string and encodes it to a string that is ok to put in a URL.
Some similar questions:
URL is accessable with browser but still FileNotFoundException with URLConnection
URLConnection FileNotFoundException for non-standard HTTP port sources
URLConnection throwing FileNotFoundException
Wish you good luck.
It returns FileNotFoundException when the server response to HTTP request is code 404.
Check your URL.

Categories