URL connection HTTP POST connection refused - java

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:
} finally {
if(connection != null) {
connection.disconnect();
}
}

I have already added it to the comments:
System.setProperty("java.net.preferIPv4Stack" , "true");
Reason: Java is using IPv6 functions on my computer but IPv4 is used for internet connection (on my computer and by my provider (T-Online)).

Related

Multiple synchronous url connections cause timeout on Apache Tomcat server

I have a server running tomcat 7, and I've noticed that whenever a client performs multiple serial requests to the server (around 10), it stops responding and causes a timeout on the client.
Seeing the server's logs, I've noticed that the server does's even receive the request.
Here is the client implementation:
try{
String http = "...";
int i;
for(i=0;i<1000;i++){
http += "?id="+ String.valueOf(i);
URL url = new URL(http);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
conn.setDoInput(true);
conn.connect();
BufferedReader inc = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = inc.readLine()) != null){
System.out.println(inputLine);
}
inc.close();
conn.disconnect();
}
br.close();
}catch(Exception e){
e.printStackTrace();
}

Simulate URL entering on java

So I have a problem where if I type this link on the browser and hit enter, an activation happens. I just want to do the same through Java. I don't need any kind of response from the URL. It should just do the same as entering the URL on a browser. Currently my code doesn't throw an error, but I don't think its working because the activation is not happening. My code:
public static void enableMachine(String dns){
try {
String req= "http://"+dns+"/username?username=sputtasw";
URL url = new URL(req);
URLConnection connection = url.openConnection();
connection.connect();
/*BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
String strTemp = "";
while (null != (strTemp = br.readLine())) {
System.out.println(strTemp);
}*/
} catch (Exception ex) {
ex.printStackTrace();
}
}
What's the problem?
If you want to do that with an URLConnection, it isn't sufficient to just open the connection with connect, you also have to send e.g. an HTTP request etc.
That said, i think it would be easier, if you use an HTTP client like the one from Apache HttpComponents (http://hc.apache.org/). Just do a GET request with the HTTP client, this would be the same as visiting the page with a browser (those clients usually also supports redirection etc.).
You may use HttpUrlConnectionClass to do the job:
URL url = new URL("http://my.url.com");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setRequestProperty("Content-Type", "application/json");
httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");
String params = "foo=42&bar=buzz";
DataOutputStream wr = new DataOutputStream(httpCon.getOutputStream());
wr.writeBytes(params);
wr.flush();
wr.close();
httpCon.connect();
int responseCode = httpCon.getResponseCode();
You may as well use "GET" request method and just append parameters to the url.

REST HttpURLConnection

I am working on a REST Client experimenting with the tinkerpop database using using HttpURLConnection.
I am trying to send over a 'GET - CONNECT'. Now I understand (from some net research) that if I use doOutput(true) the 'client' will a 'POST' even if I setRequestMethod 'GET' as POST is the default (well ok?) however when I comment out the the doOutput(true) I get this error:
java.net.ProtocolException: cannot write to a URLConnection if doOutput=false - call setDoOutput(true)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:995)
at RestContent.handleGetConnect(RestContent.java:88)
at RestClient.main(RestClient.java:42)`
Here is the communication code snip I have tried various option with setUseDoOutPut().
//connection.setDoInput(true);
connection.setUseCaches (false);
connection.setDoOutput(true);
connection.setAllowUserInteraction(false);
// set GET method
try {
connection.setRequestMethod("GET");
} catch (ProtocolException e1) {
e1.printStackTrace();
connection.disconnect();
}
Exception at connection.setRequestMethod("GET") in the other case. Any hints?
Following code works fine: URL is a Rest URL with supported GET operation.
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
//connection.setDoOutput(true);
InputStream content = (InputStream) connection.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}

POST Requests from a Servlet

I am writing a servlet using eclipse that receives POST request from a client that should do some splitting on the received text, access google geolocation api to get some data and display to the user.
On a localhost, this works perfectly fine. On an actual server (tried with Openshift and CloudBees), this doesn't work. I can see the splitting reply but not the reply from google geolocation service. There is always an error logged into the console from google service. However, the same code works perfectly fine on localhost.
After I receive the POST request in the doPost method of the servlet, I am doing the following to access the Google GeoLocation service:
//Attempting to send data to Google Geolocation Service
URL url;
HttpURLConnection connection = null;
try {
//Create connection
url = new URL("https://www.googleapis.com/geolocation/v1/geolocate?key=MyAPI");
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request with data (output variable has the JSON data)
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes (output);
wr.flush ();
wr.close ();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response2 = new StringBuffer();
while((line = rd.readLine()) != null) {
response2.append(line);
response2.append('\r');
}
rd.close();
//Write to Screen using out=response.getWriter();
out.println("Access Point's Location = " + response2.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
if(connection != null) {
connection.disconnect();
}
Could you tell me why this is happening and how can I make this work? Should I resort to something like AJAX or is there someother work around? I am relatively new to coding and hence, trying to refrain from learning AJAX at this stage. Please let me if there's any other way of getting this to work
Your localhost has your localhost IP as a sending IP. Openshift et al has the Openshift et al IP as a sending IP. So the Google API says "I have only seen that localhost IP twice before, that's fine!", whereas it says "I have seen this Openshift IP millions of times before! NO REPLY FOR YOU!"

Java HttpURLConnection - POST with Cookie

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() ?

Categories

Resources