opening URLConnection with a particular web resource
I am not able to open a URLConnection with a particular web resource . I am getting
" java.net.ConnectException: Connection timed out:
" . Is it because of that domain is blocking the direct URL connection ? If so how they are blocking this ? below is the code snippet i wrote .
Code snippet:
import java.io.; import java.net.;
public class TestFileRead{
public static void main(String args[]){
try{
String serviceUrl = "http://xyz.com/examples.zip";
HttpURLConnection serviceConnection = (HttpURLConnection) new URL(serviceUrl).openConnection();
System.out.println(serviceConnection);
serviceConnection.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)");
DataInputStream din=new DataInputStream(serviceConnection.getInputStream());
FileOutputStream fout=new FileOutputStream("downloaded");
DataOutputStream dout=new DataOutputStream(fout);
int bytes;
while(din.available()>0){
bytes=din.readByte();
dout.write(bytes);
}
}catch(Exception ex){
ex.printStackTra开发者_Python百科ce();
}
}
}
You are probably using the proxy setup in your browser to access the Yahoo home page which explains why it works in your browser and not in your code. You require a proxy configuration for your Java application.
The simplest way would be to set the system property http.proxyHost
and http.proxyPort
when running the code (in Eclipse or when running from command line just add -Dhttp.proxyHost=your.host.com -Dhttp.proxyPort=80
) and you should be good to go. Pick up the proxy settings from your browser configuration/settings.
EDIT: This link does a decent job of explaining the possible solutions when dealing with proxies in Java.
Try this, it works fine for me, returning the index page.
String serviceUrl = "http://yahoo.com";
HttpURLConnection serviceConnection = (HttpURLConnection) new URL(serviceUrl).openConnection();
serviceConnection.addRequestProperty("User-Agent", "blah"); //some sites deny access to some pages when User-Agent is Java
BufferedReader in = new BufferedReader(new InputStreamReader(serviceConnection.getInputStream()));
精彩评论