I am trying to send a SOAP request over SSL with my own little Java client and it fails with "java.net.ConnectException: Connection refused". The same request sent with SOAPUI does not fail, I get a valid response from the server.
This is the code I am trying to run:
public static void main(String[] args) throws MalformedURLException {
System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");
SSLUtilities.trustAllHttpsCertificates();
URL wsdlURL = new URL(MY_WSDL_LOCATION);
QName serviceName = new QName(MY_QNAME, NAME_OF_SERVICE);
Service service = Service.create(wsdlURL, serviceName);
Order myOrder = service.getPort(Order.class);
BindingProvider portBP = (BindingProvider) myOrder;
String urlUsed = (String) portBP.getRequestContext().
get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY);
System.out.println("Using URL: " + urlUsed);
((BindingProvider)myOrder).getRequestContext().put(
BindingProvider.USERNAME_PROPERTY, CORRECT_USERNAME);
((BindingProvider)myOrder).getRequestContext().put(
BindingProvider.PASSWORD_PROPERTY, CORRECT_PASSWORD);
AliveRequest aliveRequest = new AliveRequest();
MerchantInfo merchInfo = new MerchantInfo();
merchInfo.setMerchantId(CORRECT_MERCHANT_ID);
aliveRequest.setMerchantInfo(merchInfo);
AliveResponse aliveResponse = myOrder.alive(aliveRequest);
}
It fails with "java.net.ConnectException: Connection refused" exception. When I build a request from the same WSDL using SOAPUI, populate the same fields with same values and enter the same basic authentication credentials, a valid response is returned.
The problem was the fact that my Java client didn't send the request through the proxy, so my own company's firewall was blocking it. Unlike my own Java client, SOAPUI actually detects the proxy settings of the system (probably reads system environment variables) when SOAPUI's proxy settings are set "auto" (default). The solution was to set the following system properties:
-Dhttps.proxySet=true
-Dhttps.proxyHost=MY_PROXY_HOST
-Dhttps.proxyPort=MY_PROXY_PORT
Related
I'm Using CXF 3.1.5, I'm trying to make it work with proxy. if there is no username and password for the proxy, then it works; if there is an username and password for the proxy, then it doesn't work. here is my code:
//to create my own http conduit
bus.setExtension(new TLSAndProxySupportedHTTPConduitFactory(settings, HTTPConduitFactory.class);
//to get wsdl definition
Definition definition = bus.getExtension(WSDLManager.class).getDefinition(uri);
TLSAndProxySupportedHTTPConduitFactory implements HTTPConduitFactory, and will create a TLSAndProxySupportedHTTPConduit which extends URLConnectionHTTPConduit, in TLSAndProxySupportedHTTPConduit, here is the related code for proxy settings:
//HTTPClientPolicy settings works
HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
httpClientPolicy.setProxyServer(proxy.getHostName());
httpClientPolicy.setProxyServerPort(proxy.getPort());
this.setClient(httpClientPolicy);
if (proxy.getUserName() != null) {
//ProxyAuthorizationPolicy settings doesn't work
this.getProxyAuthorization().setUserName(proxy.getUserName());
this.getProxyAuthorization().setPassword(proxy.getPassword());
}
Please do remember if the proxy has no username and password, everything works just fine.and if the target URL for loading WSDL definition is started with https(https is required for me), the proxy doesn't work. if it's started with http, then the proxy with username and password works well.
Find a solution:
The Reason is
The Java Secure Socket Extension (JSSE) library from Sun Microsystems lets you access a secure Web server from behind a firewall via proxy tunneling. To do this, the JSSE application needs to set the https.ProxyHost and https.ProxyPort system properties. The tunneling code in JSSE checks for "HTTP 1.0" in the proxy's response. If your proxy, like many, returns "HTTP 1.1", you will get an IOException. In this case, you need to implement your own HTTPS tunneling protocol.
Referance:http://www.javaworld.com/article/2077475/core-java/java-tip-111--implement-https-tunneling-with-jsse.html
and https://community.oracle.com/thread/1534538
Then you could overwrite method setupConnection of URLConnectionHTTPConduit.
#Override
protected void setupConnection(Message message, Address address, HTTPClientPolicy csPolicy) throws IOException {
super.setupConnection(message, address, csPolicy);
HttpURLConnection connection = (HttpURLConnection) message.get(KEY_HTTP_CONNECTION);
decorateHttpsURLConnection((HttpsURLConnection) connection);\
message.put(KEY_HTTP_CONNECTION, connection);
}
in the method decorateHttpsURLConnection:
httpsConnection.setSSLSocketFactory(new SSLTunnelSocketFactory(getProxy(), sslContext.getSocketFactory()));
I am getting this error
System.err: java.net.UnknownHostException: Unable to resolve host "proxy01": No address associated with hostname
I am using OKHTTP. My company have two internet connections. One which requires authentication. When l make OKHTTP call using the guest network, it works as expected. But when l switch network and connect to the secured network, l get the error above. I know my company have proxy server which am suspecting is preventing outgoing network call without authentication. When l connect to the secure network and authenticate with my username and password, am able to open google.com on my phone, however, when l open my app on the phone l get the above error
You need to provide proxy settings and its authenticator while working with OKHTTP, Something like this :
Authenticator proxyAuthenticator = new Authenticator() {
#Override public Request authenticate(Route route, Response response) throws IOException {
String credential = Credentials.basic(<username>, <password>);
return response.request().newBuilder()
.header("Proxy-Authorization", credential)
.build();
}
};
OkHttpClient client = new OkHttpClient.Builder()
.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(<proxyHost>, <proxyPort>)))
.proxyAuthenticator(proxyAuthenticator)
.build();
replace tokens <token> with their respective values.
I'm trying to login users using Google OpenID.
When I try to authenticate a user, I always run into a timeout when trying to retrieve the AccessToken.
public class TestRun {
public static void main(String args[]) throws OAuthSystemException, OAuthProblemException {
OAuthClientRequest request = OAuthClientRequest
.tokenProvider(OAuthProviderType.GOOGLE)
.setGrantType(GrantType.AUTHORIZATION_CODE)
.setCode("")
.setRedirectURI(Env.REST_API_LOCATION+"/login")
.setClientId(Env.CLIENT_ID)
.setClientSecret(Env.CLIENT_SECRET)
.buildQueryMessage();
OAuthClient oac = new OAuthClient(new URLConnectionClient());
OAuthAccessTokenResponse response = oac.accessToken(request);
System.out.println(response.getAccessToken());
System.out.println(response.getExpiresIn());
}
}
I always run into a ConnectException (timeout) when oac.accessToken(request) is called and don't get any more info about what's happening.
So, the problem is simple. The system on which my software runs is accessible from the internet, but outbound traffic is forced to use a proxy. As the proxy isn't a transparent one, I had to write my own implementation of HttpClient which is able to deal with a proxy and replace URLConnectionClient with it.
I am developing a SSL/TLS enabled server using the Java SimpleFramework. I am wondering how to validate client authentications on the server.
On the server side, I am extending org.simpleframework.http.core.ContainerServer and overriding the process() method as follows:
#Override
public void process(Socket socket) throws IOException {
// Ensures client authentication is required
socket.getEngine().setNeedClientAuth(true);
super.process(socket);
}
This is to make sure that clients authenticate. Note that if I remove the call to setNeedClientAuth(), my program works perfectly.
On the client side, the following code is used:
HttpClient client = new HttpClient();
Credentials defaultcreds = new UsernamePasswordCredentials("username", "password");
client.getState().setCredentials(AuthScope.ANY, defaultcreds);
GetMethod get = new GetMethod("https://url.to.server");
get.setDoAuthentication(true);
client.executeMethod(get);
When enabling authentication requirement, I get the following exception:
javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
I am guessing this relates to the fact that the passed credentials is never validated.
To summarize my question, how should I proceed to validate clients on the server?
I want to connect to as site through proxy in java. This is the code which I have written:
public class ConnectThroughProxy
{
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy ip", 8080));
public static void main(String[] args)
{
try
{
URL url = new URL("http://www.rgagnon.com/javadetails/java-0085.html");
URLConnection connection=url.openConnection();
String encoded = new String(Base64.encode(new String("user_name:pass_word").getBytes()));
connection.setDoOutput(true);
connection.setRequestProperty("Proxy-Authorization","Basic "+encoded);
String page="";
String line;
StringBuffer tmp = new StringBuffer();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line=in.readLine()) != null)
{
page.concat(line + "\n");
}
System.out.println(page);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
While trying to run this code it throws the following error:
java.lang.IllegalArgumentException: Illegal character(s) in message header value: Basic dXNlcl9uYW1lOnBhc3Nfd29yZA==
at sun.net.www.protocol.http.HttpURLConnection.checkMessageHeader(HttpURLConnection.java:323)
at sun.net.www.protocol.http.HttpURLConnection.setRequestProperty(HttpURLConnection.java:2054)
at test.ConnectThroughProxy.main(ConnectThroughProxy.java:30)
Any Idea how to do it?
If you're just trying to make HTTP requests through an HTTP proxy server, you shouldn't need to go to this much effort. There's a writeup here: http://java.sun.com/javase/6/docs/technotes/guides/net/proxies.html
But it basically boils down to just setting the http.proxyHost and http.proxyPort environment properties, either on the command line, or in code:
// Set the http proxy to webcache.mydomain.com:8080
System.setProperty("http.proxyHost", "webcache.mydomain.com");
System.setProperty("http.proxyPort", "8080");
// Next connection will be through proxy.
URL url = new URL("http://java.sun.com/");
InputStream in = url.openStream();
// Now, let's 'unset' the proxy.
System.clearProperty("http.proxyHost");
// From now on HTTP connections will be done directly.
It seems to me, that you are not using your Proxy instance at all. I think you should pass it when you are creating URLConnection instance:
URLConnection connection=url.openConnection(proxy);
Setting of environment properties http.proxy is easier and when using some 3rd party libraries without Proxy instance passing support only possible solution, but its drawback is that it is set globally for the whole process.
I was using the Google Data APIs and the only way I got the proxy settings to work was to provide ALL the parameters related to proxy, even thought they are set to be empty:
/usr/java/jdk1.7.0_04/bin/java -Dhttp.proxyHost=10.128.128.13
-Dhttp.proxyPassword -Dhttp.proxyPort=80 -Dhttp.proxyUserName
-Dhttps.proxyHost=10.128.128.13 -Dhttps.proxyPassword -Dhttps.proxyPort=80
-Dhttps.proxyUserName com.stackoverflow.Runner
Where, username and password are NOT required, and the same http and https servers are set to be the same, as well as the port number (if that's your case as well). Note that the same HTTP proxy is also provided as the HTTPS server, as well as its port number (reference from https://code.google.com/p/syncnotes2google/issues/detail?id=2#c16).
If your Java class has an instance of the class "URL", it should pick those configurations up...