In Java 1.4, I am trying to make an connection to a URL, but since I want to configure a timeout, I am using Apache's httpclient instead of the old school URLConnection.openConnection();
So I have the following:
HttpConnection conn = null;
SimpleHttpConnectionManager httpMgr = new SimpleHttpConnectionManager(true);
HostConfiguration hostConf = new HostConfiguration();
hostConf.setHost(new HttpHost("http://www.google.com"));
conn = httpMgr.getConnectionWithTimeout(hostConf, 30);
conn.open();
But seems like everytime I try to open a connection, I would get a java.net.UnknownHostException: http://www.google.com, even to google.com.
Did I do something wrong..?
I think protocol (http://) is what breaks it. Try using "www.google.com" as a host name.
HTTP CLient tutorial is here.
Related
I am trying to connect to Tigase Server, implement a client in Java using smack API.
ConnectionConfiguration config = new ConnectionConfiguration("192.32.104.93", 5222, "ELVES-D463645");
Connection connection = new XMPPConnection(config);
connection.connect();
When code reaches connect. I get following stacktrace.
stream:error (host-unknown)
at org.jivesoftware.smack.PacketReader.parsePackets(PacketReader.java:214)
at org.jivesoftware.smack.PacketReader.access$000(PacketReader.java:44)
at org.jivesoftware.smack.PacketReader$1.run(PacketReader.java:70)
No response from the server.:
at org.jivesoftware.smack.NonSASLAuthentication.authenticate(NonSASLAuthentication.java:73)
at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:230)
at org.jivesoftware.smack.Connection.login(Connection.java:366)
at com.directv.xmpp.client.poc.FirstClient.main(FirstClient.java:20)
XMPPException Occured while connecting to server No response from the server.
Can anyone please help me find, where am I going wrong. Thanks!
I found the solution to it.
I was entering the service name and hostname in wrong place.
and because my server is locally hosted. following code stub worked for connection with Tigase Server.
ConnectionConfiguration config = new ConnectionConfiguration("localhost", 5222, "yourdomain");
yourdomain shoulde be the domain name which was entered earlier while installation and configuration of the server.
Thank you all for your help though.
ConnectionConfiguration config = new ConnectionConfiguration("192.32.104.93", 5222, "ELVES-D463645");
The serviceName, third argument of the ConnectionConfiguration constructor, seems to be wrong. I would expect something like a domain here (example.com).
You did not even reach the Tigase server. The error appears to be related to either configuration of the DNS or to parameters you pass to the Smack library.
I do not know Smack API but from the error you attach it looks like you provide incorrect hostname, or at least a hostname which does not have a correct DNS entry.
This is fine and you should still be able to connect to the server if you can provide IP address as well.
Try below, or check your XMPP server Authentication setting
ConnectionConfiguration config = new ConnectionConfiguration(XMPP_HOST, XMPP_PORT);
config.setCompressionEnabled(false);
config.setSASLAuthenticationEnabled(false);
connection = new XMPPConnection(config);
Here is a code for Smack 4.3.4
XMPPTCPConnectionConfiguration conf = XMPPTCPConnectionConfiguration.builder()
.setHostAddress(InetAddress.getByName(host))
.setXmppDomain(JidCreate.domainBareFrom(Domain))
.setUsernameAndPassword("username", "password")
.setPort(5222)
.build();
AbstractXMPPConnection connection = new XMPPTCPConnection(conf);
connection.connect();
connection.login();
Context
I have a desktop JAVA application I use to upload files (blobs) to a google app blobstore.
Everything works fine with a direct connection to the Internet but it doesn't when connecting through an HTTP proxy (Squid) with authentication.
I am using httpClient 4.2.3 and I don't get any error or response. It just gets stuck when calling httpClient.execute(post).
Code
I added these lines to handle the proxy authentication and it works well when using URL to get a page:
System.setProperty("http.proxyUser", username);
System.setProperty("http.proxyPassword", password);
I tried those as well:
Authenticator.setDefault(
new Authenticator() {
#Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
username, password.toCharArray());
}
}
);
And from now on this is the same code that works when not using a proxy.
First of all I download a page where I get the url to use to post a file to the blobstore:
URL url = new URL("http://www.example.com/get-upload-url.jsp");
String urlWhereToPost=IOUtils.toString(url.openStream());
DefaultHttpClient client = new DefaultHttpClient ();
Here we prepare the multipart post:
HttpPost post
= new HttpPost( urlWhereToPost.trim() );
MultipartEntity entity
= new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart( "key"
, new FileBody(new File(jpgFilePath)
, "image/jpeg" )
);
post.setEntity((HttpEntity)entity);
And it is when calling execute that nothing happens (and it never get's to the next instruction):
HttpResponse execute = client.execute( post );
Tests
I have been trying several things but nothing worked:
In the beginning I thought the problem was using POST because GET works fine using URL()
but I tried using HttpClient to execute a GET and it gets stuck as well.
I used Wireshark to check the packets send to the proxy and I saw that when using URL() Wireshark recognizes the calls to the proxy as requests to execute a GET from the proxy. But when using httpClient it looks like the request is not well built because Wireshark shows a packet but doesn't recognize the inner request.
Then I tried building the POST using HttpURLConnection and it gets through the proxy and I get the answer from the server but it looks like I am not building it well because appengine doesn't find the file I send (but this would be another question...).
Conclusion
Anyone with the same problem? Any idea?
Your proxy settings are for the Java system classes. Apache HttpClient is supposed to be configured in a different way.
This link may help: Proxy authentication
Need timeout setting for remote data request made using java.net.URL class. After some googling found out that there are two system properties which can be used to set timeout for URL class as follows.
sun.net.client.defaultConnectTimeout
sun.net.client.defaultReadTimeout
I don't have control over all the systems and don't want everybody to keep setting the system properties. Is there any other alternative for making remote request which will allow me to set timeouts.
Without any library, If available in java itself is preferable.
If you're opening a URLConnection from URL you can set the timeouts this way:
URL url = new URL(urlPath);
URLConnection con = url.openConnection();
con.setConnectTimeout(connectTimeout);
con.setReadTimeout(readTimeout);
InputStream in = con.getInputStream();
How are you using the URL or what are you passing it to?
A common replacement is the Apache Commons HttpClient, it gives much more control over the entire process of fetching HTTP URLs.
I have an authentication protected url : www.domain.com/alias
that when requested will return another url: www.another.com/resource.mp4 (not protected)
I would like to know if exists a method in Java that will return the real url from a given one.
Something like: second = resolve(first)
I'm thinking of loading the first and try to read into the response maybe the location attribute, but since I'm not a java guru I would like to know if Java already faces this.
This is a problem i used to have concerning URL redirects. Try the following code:
URL url = new URL(url);
HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
ucon.setInstanceFollowRedirects(false);
URL secondURL = new URL(ucon.getHeaderField("Location"));
URLConnection conn = secondURL.openConnection();
The "magic" here happens in these 2 steps:
ucon.setInstanceFollowRedirects(false);
URL secondURL = new URL(ucon.getHeaderField("Location"));
By default InstanceFollowRedirects are set to true, but you want to set it to false to capture the second URL. To be able to get that second URL from the first URL, you need to get the header field called "Location".
I have eliminated this issue on sites where we have a MikroTik router by using a Layer 7 protocol filter as shown below. This doesn't help the devices off the WiFi network (obviously) but at least gives them some reprieve when they are connected to home and/or work WiFi networks.
Firstly, create the protocol definition:
/ip firewall layer7-protocol
add comment="Frigging javascript redirects on chrome browsers" \
name=Javascript_Redirect \
regexp="^.+(spaces.slimspot.com|mostawesomeoffers.com).*\$"
Now, to actually filter this traffic out
/ip firewall filter
add action=drop chain=forward comment=\
"Block and log Javascript_Redirect L7 Protocol" layer7-protocol=\
Javascript_Redirect log=yes log-prefix=JSredirect_
Other firewalls that have Layer 7 filtering capacity could also block these redirects in a similar way.
If you are using Ktor:
import io.ktor.client.statement.*
val resp = HttpClient.get<HttpResponse>(urlString = yourUrl)
val redirectedUrl = resp.request.url
I am writing a code that connects to websites and checks some code, like a crawler. But I need to connect trough a proxy and change the IP address (so it doesn't show the client's IP in the server logs).
How can this be done through java?
You can use the java system properties to set up a proxy or pass it as command line options.
You can find some details and samples here.
Ex: Before opening the connection
System.setProperty("http.proxyHost", "myProxyServer.com");
System.setProperty("http.proxyPort", "80");
Or you can use the default network proxies configured in the sytem
System.setProperty("java.net.useSystemProxies", "true");
Since Java 1.5 you can create a instance of proxy and pass it to the openConnection() method.
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("123.0.0.1", 8080));
URL url = new URL("http://www.yahoo.com");
HttpURLConnection uc = (HttpURLConnection)url.openConnection(proxy);
uc.connect();
Or as lisak suggested, you can use some 3rd party libraries which supports your need better.
Or you can also use HttpClient which would suit your needs better. Check out the documentation, it's brief and very informative.
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpHost proxy = new HttpHost("someproxy", 8080);
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("123.0.0.1", 8080));
URL url = new URL("http://www.yahoo.com");
HttpURLConnection uc = (HttpURLConnection)url.openConnection(proxy);
uc.connect();
This worked for me. I was able to use the proxy for the specific connection or transfer. Earlier we were using System.setProperty which used to set it at system level and all the requests internal/external started using the same proxy.
Also Proxy.Type.HTTP works for both http and https