Reputation: 282
How to open URL in java?
E.g i have https://www.iformbuilder.com/exzact/dataExcelFeed.php?
PAGE_ID=3175952&TABLE_NAME=_data399173_eff_sor&ANALYTIC=1&SINCE_DATE=2013-10-1
when we go to this URL it will download the file.But how to implement this thing in code?
I try this to open url so that file will be downloaded.But its not working.
URL url = new URL("https://www.iformbuilder.com/exzact/dataExcelFeed.php?PAGE_ID=3175952&TABLE_NAME=_data399173_eff_sor&ANALYTIC=1&SINCE_DATE=2013-10-16");
HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
System.out.println(urlCon);
urlCon.connect();
I know something is wrong But i dont knw whats dat
Upvotes: 2
Views: 1434
Reputation: 202
You can use this code:
try {
//specify the protocol along with the URL
URI oURL = new URI("https://www.google.com/");
desktop.browse(oURL);
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Upvotes: 0
Reputation: 17380
Try this:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
class HttpHelperx
{
public static String GET(String url)
{
String result = "";
try
{
URL navUrl = new URL(url);
URLConnection con = (URLConnection)navUrl.openConnection();
result = getContent(con);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return result;
}
public static String getContent(URLConnection con)
{
String result = "";
if(con!=null)
{
BufferedReader br;
try
{
br = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder buffer = new StringBuilder();
String aux = "";
while ((aux = br.readLine()) != null)
{
buffer.append(aux);
}
result = buffer.toString();
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return result;
}
}
To use it:
public class HTTPHelperDriver
{
public static void main(String[] args)
throws Exception
{
String response = HttpHelperx.GET("http://www.google.com");
System.out.println(response);
}
}
Upvotes: 1
Reputation: 1777
I have found this:
URL website = new URL("http://www.website.com/information.asp");
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream("information.html");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
In this article: How to download and save a file from Internet using Java?
I hope this helps you
Upvotes: 2