I am working on a Java desktop application with Java 7. For my application, I want to send data with POST to a server (using HTTP). The server is running on my local machine on localhost.
But if I am trying to connect to the server, an connection reset (SocketTimeoutException) is returned. I can`t connect, I have also tried to connect to a webpage like http://www.google.de, but it also fails. The var body contains the POST data in correct form. (I have also tried to connect with disabled firewall)
My code:
body=body.substring(0,body.length()-2);
HttpURLConnection connection = null;
try {
if (revision){ //Connect to the revision server
this.urlRevision = new URL(this.settingsRevision.getAddress());
connection = (HttpURLConnection) urlRevision.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(10000);
connection.setReadTimeout(10000);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", String.valueOf(body.length()));
connection.connect();
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(body);
writer.flush();
this.returnedData = new BufferedReader(new InputStreamReader(connection.getInputStream()));
for(String line; (line = returnedData.readLine()) != null;){
System.out.println(line);
}
writer.close();
this.returnedData.close();
}
} catch (Exception e) {
this.exception=e;
}
You should try close the connection like this: