5

I am trying to make a simple http request using HttpURLConnection. I am getting this error, connection timed out. I am using intellij IDEA, and set the proxy properly. Check connection in the settings, says the connection is success. What might have gone wrong? Here is my code.

import java.io.*;
import java.net.*;

/**
 * Created by admin on 22/8/15.
 */
public class Hello {
    public static void main(String [] args)
    {
        try
        {
            URL url = new URL("http://www.google.com");
            URLConnection urlConnection = url.openConnection();
            HttpURLConnection connection = null;
            if(urlConnection instanceof HttpURLConnection)
            {
                connection = (HttpURLConnection) urlConnection;
            }
            else
            {
                System.out.println("Please enter an HTTP URL.");
                return;
            }
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(connection.getInputStream()));
            String urlString = "";
            String current;
            while((current = in.readLine()) != null)
            {
                urlString += current;
            }
            System.out.println(urlString);
        }catch(IOException e)
        {
            e.printStackTrace();
        }
    }
}

The error is the following

java.net.ConnectException: Connection timed out
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
    at java.net.Socket.connect(Socket.java:529)
    at java.net.Socket.connect(Socket.java:478)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:163)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:394)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:529)
    at sun.net.www.http.HttpClient.<init>(HttpClient.java:233)
    at sun.net.www.http.HttpClient.New(HttpClient.java:306)
    at sun.net.www.http.HttpClient.New(HttpClient.java:323)
    at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:860)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:801)
    at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:726)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1049)
    at Hello.main(Hello.java:24)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

Process finished with exit code 0

ps: Using system properties in the code does work. But it is not feasible for my purposes. Is there any work around for this. I don't want to write code like the following, i.e., removing some lines from production. And the following works fine.

import java.io.*;
import java.net.*;
import java.util.Properties;

/**
 * Created by admin on 22/8/15.
 */
public class Hello {

   // This method should be removed in production
    static void setProxy(){
        Properties systemProperties = System.getProperties();
        systemProperties.setProperty("http.proxyHost","lotus");
        systemProperties.setProperty("http.proxyPort", "8080");
    }
    public static void main(String [] args)
    {
        try
        {

            setProxy();
            URL url = new URL("http://www.google.com");
            URLConnection urlConnection = url.openConnection();
            HttpURLConnection connection = null;
            if(urlConnection instanceof HttpURLConnection)
            {
                connection = (HttpURLConnection) urlConnection;
            }
            else
            {
                System.out.println("Please enter an HTTP URL.");
                return;
            }
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(connection.getInputStream()));
            String urlString = "";
            String current;
            while((current = in.readLine()) != null)
            {
                urlString += current;
            }
            System.out.println(urlString);
        }catch(IOException e)
        {
            e.printStackTrace();
        }
    }
}
gates
  • 4,465
  • 7
  • 32
  • 60
  • possible duplicate of [How do I make HttpURLConnection use a proxy?](http://stackoverflow.com/questions/1432961/how-do-i-make-httpurlconnection-use-a-proxy) –  Aug 31 '15 at 05:55
  • I don't want to use proxy in my code, it is not feasible for my purpose @RC – gates Aug 31 '15 at 05:57
  • I tested your code on my IntelliJ 11 and it worked fine. – Tim Biegeleisen Aug 31 '15 at 06:03
  • Yes, it works fine when using system properties in my code. But when removed those lines from the code, it does not work @TimBiegeleisen – gates Aug 31 '15 at 06:04
  • Importing 'java.io.*' and 'java.net.*' is a bad practice. You should be more specific by importing what you really need. – Yodism Aug 31 '15 at 06:11
  • Compiler does not take care of that? @camelCase – gates Aug 31 '15 at 06:14
  • @gates, are you saying that you need proxy settings for testing, but need to remove them for production? – Jason Aug 31 '15 at 06:15
  • I noticed that importing all classes is taking too long compare to importing specific classes. @gates – Yodism Aug 31 '15 at 06:18
  • yes, but more specifically I need to be able to put the proxy in the IDE rather than the code. If I need to remove the code in the production, what are the strategies available for me? @Jason – gates Aug 31 '15 at 06:20
  • I don't think so, as you don't compile every time. Anyway that's another debate @camelCase – gates Aug 31 '15 at 06:21
  • Yess. If I asked this on this site, It might be flagged as too broad. :D @gates – Yodism Aug 31 '15 at 06:39
  • 1
    Wildcard imports are a bad practice, because it is harder to see where a referenced class comes from. You can't then see if it is a class from the same package or from a library. And it is easier to unintentionally hide library class if you have equal names in your package. – Tom Aug 31 '15 at 08:37
  • Will follow the practice, thanks – gates Aug 31 '15 at 08:50

1 Answers1

0

Create two properties files with the same name (proxy.properties). Use the one that contains:

http.proxyHost=lotus
http.proxyPort=8080

... for development and the one that contains:

http.proxyHost=
http.proxyPort=

should be shipped to prod.

Then in your class above:

static Proxy getProxy() throws IOException {
    Properties proxyProperties = new Properties();
    InputStream inputStream = null;
    try {
        inputStream = Hello.getClass().getClassLoader().getResourceAsStream("proxy.properties");
        proxyProperties.load(inputStream);
    } finally {
        if(inputStream != null) {
            try {
                inputStream.close();
            } catch(IOException ioe) {
            }
        }
    }
    String proxyHost = proxyProperties.getProperty("http.proxyHost");
    if(proxyHost != null && proxyHost.length() > 0)) {
        String proxyPort = proxyProperties.getProperty("http.proxyPort");
        SocketAddress addr = new InetSocketAddress(proxyHost, Integer.parseInt(proxyPort));
        return new Proxy(Proxy.Type.HTTP, addr);
    }
    return null;
}

Then in your main method:

...
URL url = new URL("http://www.google.com");
URLConnection urlConnection;
Proxy = getProxy();
if(proxy != null) {
    urlConnection = url.openConnection(proxy);
} else {
    urlConnection = url.openConnection();
HttpURLConnection connection = null;
...
Jason
  • 11,744
  • 3
  • 42
  • 46