国产探花免费观看_亚洲丰满少妇自慰呻吟_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();
 }

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 西吉县| 兴宁市| 望城县| 正镶白旗| 乌拉特后旗| 邮箱| 楚雄市| 邹城市| 焦作市| 宁晋县| 怀安县| 金秀| 苍梧县| 马山县| 高陵县| 汉源县| 璧山县| 新干县| 柞水县| 阜南县| 加查县| 左权县| 七台河市| 易门县| 健康| 巨鹿县| 镇远县| 广河县| 深水埗区| 策勒县| 富宁县| 万源市| 盐亭县| 遂溪县| 芜湖市| 宁晋县| 中超| 阜新市| 南安市| 丰顺县| 桦川县|