?
Solved

Malformed Reply from SOCKS Server when fetching proxy server details dynamically

Posted on 2017-07-31
16
Low Priority
?
125 Views
Last Modified: 2017-08-08
I am trying to access a website through proxy server.I am using httpclient.

This is the code which is working fine:

import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Properties;

public class Working {
private static  String PROXY_HOST = "proxy.test.org";
private static  int PROXY_PORT = 80;

    public static void main(String[] args) {
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod("https://www.example.org");
    HostConfiguration config = client.getHostConfiguration();
    config.setProxy(PROXY_HOST, PROXY_PORT);

    try {
          client.executeMethod(method);
            if (method.getStatusCode() == HttpStatus.SC_OK) {
           String response = method.getResponseBodyAsString();
           System.out.println("Response = " + response);
                        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        method.releaseConnection();
    }
    System.out.println("end");
    }
}

But When I use following method to set PROXY_HOST and PROXY_PORT values dynamically I am getting "Malformed reply from SOCKS server" exception

public static void getProxyDetails()
{
    Properties systemSettings = System.getProperties();
    systemSettings.put("proxySet", "true");
    try {
        Proxy proxy = (Proxy) ProxySelector.getDefault().select(new URI(
                "https://www.example2.com/xyz")).iterator().
             next();
         System.out.println("proxy hostname : " + proxy.type());
          InetSocketAddress addr = (InetSocketAddress)proxy.address();
          if (addr == null) {
              System.out.println("No Proxy");
           } else {
              System.out.println("proxy hostname : " + addr.getHostName());
              System.out.println("proxy port : " + addr.getPort());
               PROXY_HOST = addr.getHostName();
               PROXY_PORT = addr.getPort();            
           }
    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

I tried other suggestions provided on the internet but it didn't solve my issue. Am I making any mistake in the code?.Any help is appreciated.
0
Comment
Question by:nak nak
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 6
16 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 42236919
But When I use following method to set PROXY_HOST and PROXY_PORT values dynamically
Those values are not being set at all in the (misleadingly-named) method 'getProxyDetails'
0
 

Author Comment

by:nak nak
ID: 42236941
@CEHJ, I am able to print and see the values of PROXY_HOST  and PROXY_PORT and these have expected values.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 42236966
As i said, your code does not set them
0
Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

 

Author Comment

by:nak nak
ID: 42237021
In the question I have not included code to call the getProxyDetails() method but I have mentioned I am calling the said method. In my workspace I am calling getProxyDetails() from main() and then printing the values of PROXY_HOST and PROXY_PORT, these have expected values. now when I pass  PROXY_HOST and PROXY_PORT to setProxy() and then try to call client.execute(method) the execute()  is throwing said exception. but if i hard code host and port values I am not getting the exception and the code works as expected. I don't know why i am getting the exception when I am not hard coding the values.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 42237029
Let's try it this way: please show me the lines in the above code, where you SET those properties. You can just quote the two lines
0
 

Author Comment

by:nak nak
ID: 42237061
PROXY_HOST = addr.getHostName(); PROXY_PORT = addr.getPort(); inside getProxyDetails(). I my workspace I have called this method inside main()
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 1000 total points
ID: 42237133
a. that's setting static variables in your class, not networking properties
b. i don't see any sign of getProxyDetails() being called at all

I'd
a. rename the method setProxyDetails (that's its intent)
b. pass that method an instance of HostConfiguration and use that parameter
0
 

Author Comment

by:nak nak
ID: 42238552
@CEHJ passing HostConfiguration reference to the method doesn't fix the problem either. Was able to solve the problem using HttpURLConnection instead of HttpClient. Thanks for your time.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 42238555
For the benefit of future visitors, please post your revised code
0
 

Author Comment

by:nak nak
ID: 42238589
This is the working code using HttpURLConnection :

package com.antares;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Properties;

import javax.net.ssl.HttpsURLConnection;

public class URLWithProxy {
	public static String Proxy = "";
	public static int port = 0;
	
	public static void setProxyDetails()
    {
    	System.setProperty("java.net.useSystemProxies", "true");
        Properties systemSettings = System.getProperties();
        systemSettings.put("proxySet", "true");
        try {
			Proxy proxy = (Proxy) ProxySelector.getDefault().select(new URI(
			        "https://www.dummy.in")).iterator().
			     next();
			 System.out.println("proxy hostname : " + proxy.type());
		      InetSocketAddress addr = (InetSocketAddress)proxy.address();
		      if (addr == null) {
		          System.out.println("No Proxy");
		       } else {
		    	   Proxy = addr.getHostName();
		    	   port = addr.getPort();
		    	   
		    	   
		       }
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

	 private static void print_content(HttpsURLConnection con){
			if(con!=null){

			try {

			   System.out.println("****** Content of the URL ********");
			   BufferedReader br =
				new BufferedReader(
					new InputStreamReader(con.getInputStream()));

			   String input;

			   while ((input = br.readLine()) != null){
			      System.out.println(input);
			   }
			   br.close();

			} catch (IOException e) {
			   e.printStackTrace();
			}

		       }
	 }
	 
	public static void main(String[] args) {
		getProxyDetails();
		
		InetSocketAddress proxyInet = new InetSocketAddress(Proxy,port);
		Proxy proxy = new Proxy(java.net.Proxy.Type.HTTP, proxyInet);		
		 URL url=null;
	     String sUrl = "https://www.dummy.in";
	     try {
	     url = new URL(sUrl);
	     try {
			HttpsURLConnection conn = (HttpsURLConnection)url.openConnection(proxy);
			print_content(conn);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	     
	     } catch (MalformedURLException e) {
	     // TODO Auto-generated catch block
	     e.printStackTrace();
	     }
	    	     
	}

}

Open in new window

0
 

Author Comment

by:nak nak
ID: 42238597
line number 71 should be setProxyDetails(); not getProxyDetails();
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 42238640
    setProxyDetails();

        InetSocketAddress proxyInet = new InetSocketAddress(Proxy, port
);

That's the reason your code now works (nothing to do with HttpClient/HttpURLConnection): you now use the variables after setting them, which you were not doing before (as i told you)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 42246785
https://www.experts-exchange.com/questions/29047620/Malformed-Reply-from-SOCKS-Server-when-fetching-proxy-server-details-dynamically.html#a42237133
contains the best answer. It's conceivable i didn't express myself clearly, but for the record: the OP was setting the variables, but those were not propagated to the actual networking properties concerned
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A few customers have recently asked my thoughts on Password Managers.  As Security is a big part of our industry I was initially very hesitant and sceptical about giving a program all of my secret passwords.  But as I was getting asked about them mo…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
Suggested Courses

649 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question