thieumao

HttpURLConnectionExample.java - get HTML String from Website

Mar 13th, 2014
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.29 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.InputStreamReader;
  3. import java.net.HttpURLConnection;
  4. import java.net.URL;
  5.  
  6. public class HttpURLConnectionExample {
  7.     private final String USER_AGENT = "Mozilla/5.0";
  8.  
  9.     public static void main(String[] args) throws Exception {
  10.  
  11.         HttpURLConnectionExample http = new HttpURLConnectionExample();
  12.  
  13.         System.out.println("Testing 1 - Send Http GET request");
  14.         System.out.println(http.sendGet("http://m.mytv.vn/"));
  15.  
  16.     }
  17.  
  18.     // HTTP GET request
  19.     private String sendGet(String url) throws Exception {
  20.  
  21.         URL obj = new URL(url);
  22.         HttpURLConnection con = (HttpURLConnection) obj.openConnection();
  23.  
  24.         // optional default is GET
  25.         con.setRequestMethod("GET");
  26.  
  27.         // add request header
  28.         con.setRequestProperty("User-Agent", USER_AGENT);
  29.  
  30.         int responseCode = con.getResponseCode();
  31.         System.out.println("\nSending 'GET' request to URL : " + url);
  32.         System.out.println("Response Code : " + responseCode);
  33.  
  34.         BufferedReader in = new BufferedReader(new InputStreamReader(
  35.                 con.getInputStream()));
  36.         String inputLine;
  37.         StringBuffer response = new StringBuffer();
  38.  
  39.         while ((inputLine = in.readLine()) != null) {
  40.             response.append(inputLine);
  41.         }
  42.         in.close();
  43.  
  44.         // print result
  45.         return response.toString();
  46.         // System.out.println();
  47.  
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment