Getting Connection refused while running my code,

2019-06-12 10:29发布

问题:

//This is my code for returning json response from twitter api which works fine when i am not behind any proxy server 

import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;

public class TwitterFeeds {

    static String AccessToken = "xxxx";
    static String AccessSecret = "xxxx";
    static String ConsumerKey = "xxxx";
    static String ConsumerSecret = "xxxx";

    public static void main(String[] args) throws Exception { 
        OAuthConsumer consumer = new CommonsHttpOAuthConsumer(ConsumerKey, ConsumerSecret);
        consumer.setTokenWithSecret(AccessToken, AccessSecret);

        HttpGet request = new     HttpGet("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=xxxx&count=2"); 

        consumer.sign(request);
        HttpClient client = new DefaultHttpClient();       
        HttpResponse response = client.execute(request);
        String json_string = EntityUtils.toString(response.getEntity());
        System.out.println(json_string);
        JSONArray  obj = new JSONArray (json_string);
        System.out.println(obj.toString());
    }
}

// I am behind a proxy server which is blocking my request, the code works fine when i am not behind any proxy server.And getting following error

Exception in thread "main" org.apache.http.conn.HttpHostConnectException: Connection to https://api.twitter.com refused
    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:158)
    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:149)
    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:121)
    at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:562)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:415)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:820)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:754)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:732)
    at TwitterFeeds.main(TwitterFeeds.java:47)
Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:374)
    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:148)
    ... 8 more

This is error which i ma getting showing connection refused. and the code for getting tweets(json format) by user and works when i am not behind any proxy server and does not work when i am behind proxy server

回答1:

I believe that your HttpGet request is missing your proxy settings.

You should do the following:

// Here you set your proxy host and port
HttpHost proxy = new HttpHost(<your_proxy_addess>, <port>); 
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
HttpClient client = HttpClients.custom().setRoutePlanner(routePlanner).build();
HttpResponse response = client.execute(request);

If you see that's necessary to provide any type of proxy credentials, then the following approach should be taken:

  • Create your HttpGet request

    HttpHost proxy = new HttpHost(<your_proxy_addess>, <port>);
    RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
    HttpGet request = new HttpGet("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=xxxx&count=2");
    request.setConfig(config);
    
  • Provide your credentials to your HttpClient:

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
            new AuthScope(<your_proxy_addess>, <port>),
            new UsernamePasswordCredentials("user", "passwd"));
    
    HttpClient client = HttpClients.custom()
            .setDefaultCredentialsProvider(credsProvider).build();
    HttpResponse response = client.execute(request);
    


回答2:

I think you're on the right track with the proxy error.

In java, there is at least 2-3 ways to "bypass" the proxy. Each of them have they advantages and inconvenients :

  1. Passing arguments to the JVM :
$ java -Dhttp.proxyHost=webcache.example.com -Dhttp.proxyPort=8080 -Dhttp.proxyUser=someUserName -Dhttp.proxyPassword=somePassword 

By doing this, all HTTP connections are affected by this settings. You can have a more slightly dynamic method by following the next point.

  1. Using System.setProperty(String, String) :

Like the method above, you can set and unset properties to the JVM but now directly in the code like so.

//Set the http proxy to webcache.example.com:8080
System.setProperty("http.proxyHost", "webcache.example.com");
System.setProperty("http.proxyPort", "8080");

// Now, let's 'unset' the proxy.
System.setProperty("http.proxyHost", null);

This is a great solution if you want to keep everything simple and if your application isn't multi-thread. Like I said before, properties are set for all the JVM.

  1. Using the Proxy class :

This solution is more flexible than the two other one.

SocketAddress addr = new InetSocketAddress("webcache.example.com", 8080);
Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);      
URL url = new URL("http://java.example.org/");
URConnection conn = url.openConnection(proxy);

Note: for HTTPS, simply use Proxy.Type.HTTPS. For the other methods, use https.proxyPort instead of http.proxyPort (for example)