国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

FileUtils擴展readURLtoString讀取url內容

2019-11-26 15:46:06
字體:
來源:轉載
供稿:網友

復制代碼 代碼如下:

/**
  * 因為FileUtils不支持,所以添加個方法 String content =
  * FileUtils.readFileToString(FileUtils.toFile(new
  * URL("http://www.baidu.com")));
  *
  * @param source
  * @param encoding
  * @return
  * @throws IOException
  */
 public static String readURLToString(URL source) throws IOException {
  return readURLToString(source,null);
 }
 /**
  * 因為FileUtils不支持,所以添加個方法
  *
  * <pre>
  * String content = FileUtils.readFileToString(FileUtils.toFile(new URL(
  *   "http://www.baidu.com")), "gb2312");
  * </pre>
  *
  * @param source
  * @param encoding
  * @return
  * @throws IOException
  */
 public static String readURLToString(URL source, String encoding)
   throws IOException {
  InputStream input = source.openStream();
  try {
   return IOUtils.toString(input, encoding);
  } finally {
   IOUtils.closeQuietly(input);
  }
 }
 /**
  * 讀取url的內容(method為post,可指定多個參數)
  * @param url
  * @param encoding
  * @param params map的參數(key為參數名,value為參數值)
  * @return String
  * @throws IOException
  */
 public static String readURLToStringByPOST(URL url, String encoding,Map<String, String> params)
 throws IOException {
  HttpURLConnection con = null;
  // 構建請求參數
  StringBuffer sb = new StringBuffer();
  if (params != null) {
   for (Entry<String, String> e : params.entrySet()) {
    sb.append(e.getKey());
    sb.append("=");
    sb.append(e.getValue());
    sb.append("&");
   }
   if(sb.length()>0){
    sb.substring(0, sb.length() - 1);
   }
  }
  // 嘗試發送請求
  try {
   con = (HttpURLConnection) url.openConnection();
   con.setRequestMethod("POST");
   con.setDoOutput(true);
   con.setDoInput(true);
   con.setUseCaches(false);
   con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
   OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(),encoding);
   if (params != null) {
    osw.write(sb.toString());
   }
   osw.flush();
   osw.close();
  } catch (Exception e) {
   LogFactory.getLog(FileUtils.class).error("POST("+url.toString()+")Error("+e.getMessage()+")",e);
  } finally {
   if (con != null) {
    con.disconnect();
   }
  }
  // 讀取返回內容
  StringBuffer buffer = new StringBuffer();
  try {
   BufferedReader br = new BufferedReader(new InputStreamReader(con
     .getInputStream(),encoding));
   String temp;
   while ((temp = br.readLine()) != null) {
    buffer.append(temp);
    buffer.append("/n");
   }
  } catch (Exception e) {
   e.printStackTrace();
  }

  return buffer.toString();
 }

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 新和县| 屏东市| 白水县| 九龙县| 兴和县| 大同市| 和平县| 黄平县| 钦州市| 开阳县| 深水埗区| 鄱阳县| 安乡县| 鄂托克前旗| 宜兰市| 介休市| 长顺县| 襄樊市| 凤城市| 藁城市| 雷波县| 漠河县| 四川省| 阿尔山市| 祥云县| 八宿县| 许昌县| 庆城县| 正镶白旗| 垫江县| 新乡市| 岑巩县| 新田县| 绥中县| 晋宁县| 万年县| 台州市| 铜梁县| 连平县| 资阳市| 玉林市|