I want to do something after timeout. but my code is not doing anything and it's just keep trying to connect...
try {
URL url = new URL(p1[0]);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream in = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader( in ));
res = br.readLine();
}
} catch (IOException e) {
Global.mkOkDialog(c, "Couldn't connect to server.");
e.printStackTrace();
}
the message above in catch block not showing at all after 5 seconds
First of all, you don' actually connect to anything, you should call con.connect(). Catch block gets executed only in case of IOException which is not happening.
With if(con.getResponseCode()==HttpURLConnection.HTTP_OK) you're checking if the HTTP-Response-Code is 200, which it is if you get an ok-response. Any other response code is not handled by your program and thus does not execute any further code.
Related
I am trying to get data from an MySQL database using a php-file. My java code is as follows:
HttpURLConnection conn = null;
URL url = null;
try {
url = new URL(getURL);
System.out.println(getURL);
conn = (HttpURLConnection)url.openConnection();
//conn.setReadTimeout(READ_TIMEOUT);
//conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput method depict handling of both send and receive
conn.setDoInput(true);
conn.setDoOutput(true);
// Append parameters to URL
Uri.Builder builder = new Uri.Builder();
builder.appendQueryParameter("user", USER);
builder.appendQueryParameter("pass", PASS);
builder.appendQueryParameter("server", SERVER);
builder.appendQueryParameter("db", DB);
String query = builder.build().getEncodedQuery();
// Open connection for sending data
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
result = reader.readLine();
return(result);
}else{
return("unsuccessful");
}
When I go to my url (hidden in the variable getURL) using a browser, I see string of json on my screen, just as it should. However, when I output the contents of the reader (above code only takes the first line, but by adapting the code I can, of course, output more) it shows the html-code for a website displaying a 404 - Page does not exist message.
Anyone has any idea what goes wrong? Yes, I did check for typo's.
Okay, I have no clue what happened, as I didn't change anything. But all of the sudden it started working?!?
Must have been something server-side I guess...
Thanks for the input and sharing your thoughts!
I have two raspberry pi´s uploading content to a webpage from the same router, which occasionally makes them block access for each other. To prevent this in java, you would normally use threads and synchronize, wait/notify and all that - but how can you do that, when the applications don´t know about each others excistens? -
My code looks something like that - and works otherwise as expected.
public void sendStrings(String output) {
String url2 = "http://myhomepage.com";
HttpURLConnection connection = null;
try {
URL obj = new URL(url2);
connection = (HttpURLConnection) obj.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.connect();
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(output);
writer.flush();
writer.close();
InputStream input = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String otherLine;
int responseCode = connection.getResponseCode();
}
catch (IOException e) {
} finally {
connection.disconnect();
}
}
I have tried to fix this problem but i didn't get a good solution for this.
I just opened a socket with httsurlconnection and closed.
However, the socket i opened didn't close and the socket state was CLOSE_WAIT.
Here is my code and air log for this.
What is wrong with my code?
String https_url = "https://www.google.com";
URL url = new URL(https_url);
try {
con = (HttpsURLConnection) url.openConnection();
con.setRequestProperty("Connection", "close");
if(con!=null){
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String input = br.readLine();
while(input.length() != 0)
{
input = br.readLine();
}
br.close();
con.disconnect();
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You must surly be getting a NullPointerException from this code. You must test the result of readLine() for null before doing anything else. I don't see what the point of testing for an empty line in an HTML page is.
Since update to Ice Cream Sandwich, my POST request doesn't work anymore. Before ICS, this works fine:
try {
final URL url = new URL("http://example.com/api/user");
final HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(false);
connection.setDoInput(true);
connection.setRequestProperty("Content-Length", "0");
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.w(RestUploader.class.getSimpleName(), ": response code: " + connection.getResponseMessage());
} else {
final BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
final String line = reader.readLine();
reader.close();
return Long.parseLong(line);
}
} catch (final MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (final ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (final IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return -1;
I've tried to set
connection.setDoOutput(true);
but it doesn't works. The server response is always a 405 (Method not allowed) and the server log says it was an GET request.
The Android JavaDoc to setRequestMethod says:
This method can only be called before the connection is made.
Does it mean that the method must be invoked before url.openConnection()? How should I create a HttpURLConnection instance? All the examples I've seen, make it as described above.
I hope someone has an idea why it always send a GET request instead of a POST.
Thanks in advance.
connection.setRequestMethod("POST");
connection.setDoOutput(false);
In above two statements just place
connection.setDoOutput(true)
before
connection.setRequestMethod("POST")
statement
My .htaccess had a rewrite rule which redirected www to http://. Turned out my Java code worked just fine! The redirect/rewrite rule made my 1st request (POST) to forward to http and therefore "became" a GET. My PHP script was listening to POST only, and man did I scratch my head until I found my own mistake having that redirect rule. Check yours for this kind of "problem".
For me, setting either setDoOutput or setRequestMethod first does not matter, any order works (API 23). At the moment things are in this order:
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setInstanceFollowRedirects(false);
con.setUseCaches(false);
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setRequestProperty("Content-Type",bla bla
con.setRequestProperty("Accept-Charset", "UTF-8");
con.setRequestProperty("Content-Length", String.valueOf(PARAMETER_VARIABLE.getBytes().length));
con.setFixedLengthStreamingMode(PARAMETER_VARIABLE.getBytes().length);
OutputStream os = con.getOutputStream();
os.write(PARAMETER_VARIABLE.getBytes());
os.flush();
os.close();
I´m trying to send a post request with cookies. This is the code:
try {
String query = URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode("value", "UTF-8");
String cookies = "session_cookie=value";
URL url = new URL("https://myweb");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestProperty("Cookie", cookies);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(query);
out.flush();
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
in.close();
// Send the request to the server
//conn.connect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The problem is the request is sent without the cookies. If I only make:
conn.connect(); and don´t send data, the cookies are sent OK.
I can´t check exactly what is happening, because the connection is thorugh SSL. I only check the response.
According to the URLConnection javadoc:
The following methods are used to access the header fields and the
contents AFTER the connection is made to the remote object:
* getContent
* getHeaderField
* getInputStream
* getOutputStream
Have you confirmed that in your test case above the request is getting to the server at all? I see you have the call to connect() after getOutputStream() and commented-out besides. What happens if you uncomment it and move up before the call to getOutputStream() ?