General J2EE: Make an HTTP connection from a Java standalone application

  1. Hello, What would be a simple way to make an HTTP connection to a website from a standalone Java application and to check if the response code is 200 (success) ? Thank you, Sorin
  2. Use HTTPClient : http://jakarta.apache.org/commons/httpclient/
  3. Ooops may be a little bit to heavy for your need. Simply use an HttpURLConnection : http://java.sun.com/j2se/1.5.0/docs/api/java/net/HttpURLConnection.html
  4. Thanks Guillaume, I'm using an HttpURLConnection and I get an java.net.UnknownHostException in the line "if ...." (see below). Is it because I'm behind a firewall ? And if so, how can I solve this ? Thank you, Sorin // example urlString: "http://www.yahoo.com" URL url = new URL(urlString); //Get an input stream for reading InputStream in = url.openStream(); urlConnection = (HttpURLConnection)url.openConnection(); if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { BufferedReader in = new BufferedReader (new InputStreamReader(urlConnection.getInputStream())); }
  5. If you are behind a firewall, you need to have the proxyHost and proxyPort variables set as follows: http.proxyHost=webcache http.proxyPort=8080 https.proxyHost=webcache https.proxyPort=8080 You can do this by using the command line flag -D or by using calls to System.setProperty().
  6. Thank you Ajay. So I do the following: System.setProperty("http.proxyHost", "webcache"); System.setProperty("http.proxyPort", "8080"); System.setProperty("https.proxyHost", "webcache"); System.setProperty("https.proxyPort", "8080"); .... and then my original code: URL url = new URL(newUrlString.toString()); urlConnection = (HttpURLConnection)url.openConnection(); urlConnection.connect(); if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { BufferedReader in = new BufferedReader (new InputStreamReader(urlConnection.getInputStream())); } ... and I get the same error (java.net.UnknownHostException) at the line: urlConnection.connect(); If I remove this line, I get the error at urlConnection.getResponseCode(). What am I doing wrong ? Thank you, Sorin
  7. Did you replace 'webcache' and '8080' by the hostname and port of your proxy server ? Did you check that the host your URL relates to is reachable from your computer ?
  8. Sorry, my fault[ Go to top ]

    Guillaume, you're perfectly right. I forgot to use my proxy server. Now it works. Thanks a lot, Sorin
  9. my solution is...[ Go to top ]

    Use my ClientHttpRequest from myjavatools.com