扩展readURLtoString读取url FileUtils扩展readURLtoString读取url内容

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

扩展readURLtoString读取url FileUtils扩展readURLtoString读取url内容

  2021-03-19 我要评论
想了解FileUtils扩展readURLtoString读取url内容的相关内容吗,在本文为您仔细讲解扩展readURLtoString读取url的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:读取url,下面大家一起来学习吧。

复制代码 代码如下:

/**
  * 因为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();
 }

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们