使用HttpURLConnection訪問網絡資源,返回字符串內容

package utils;java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;網絡

/**
 * 抓取指定URL新聞頁面的新聞數據
 *
 * @author  何佳偉 *
 */
public class DataCapture {url

 /**
  * 使用HttpURLConnection訪問網絡資源,返回字符串內容
  *
  * @param  trim
  * @return  結果
  */
 public static String getNewsData(String trim) {
  String result = "";// 返回的數據結果.net

  URL url = null;
  HttpURLConnection con = null;
  InputStream is = null;orm

  try {
   url = new URL(trim);
   con = (HttpURLConnection) url.openConnection();
   is = con.getInputStream();資源

   InputStreamReader isr = new InputStreamReader(is);
   BufferedReader bf = new BufferedReader(isr);字符串

   String line = "";
   while ((line = bf.readLine()) != null) {
    result += line;
   }
  } catch (MalformedURLException e) {
   e.printStackTrace();
  }get

  catch (IOException e) {
   e.printStackTrace();
  } finally {
   if (is != null) {
    try {
     is.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }io

   if (con != null) {
    con.disconnect();
   }
  }
  return result;
 }
}
form

相關文章
相關標籤/搜索