Tuesday

Get URL content

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.HttpURLConnection;

public class Test {
       public static void main(String[] args) {
             
              BufferedWriter bw = null;
              BufferedReader br = null;
              String inputLine;

              try {
                     //If you are behind a proxy you should set the following settings.
                     //You can look my other post to learn your own proxy infos
//                   System.setProperty("http.proxyHost", "your proxy host");
//                   System.setProperty("http.proxyPort", "your proxy port");
                    
                     URL url = new URL("http://lesstalkmorecode.blogspot.com.tr/");
                     HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                     conn.setReadTimeout(10*1000);
                     conn.setConnectTimeout(5*1000);
                    
                     InputStream in = conn.getInputStream();
                     br = new BufferedReader(new InputStreamReader(in));

                     String fileName = "/users/content.html";
                     File file = new File(fileName);
                     if (!file.exists())
                           file.createNewFile();

                     FileWriter fw = new FileWriter(file.getAbsoluteFile());
                     bw = new BufferedWriter(fw);
                    
                     while ((inputLine = br.readLine()) != null)
                           bw.write(inputLine);
                    
              } catch (MalformedURLException e) {
                     //log
                    
              } catch (IOException e) {
                     //log
                    
              } finally {
                    
                     try {
                           if(bw != null)
                                  bw.close();
                          
                           if(br != null)
                                  br.close();
                          
                     } catch (IOException e) {
                           //log
                     }
                    
              }

       }
}

No comments:

Post a Comment