FileUtils扩展readURLtoString读取url内容
更新时间:2014年01月17日 09:45:43 作者:
这篇文章主要介绍了FileUtils扩展readURLtoString使用其支持读取URL内容为String,支持带POST传大量参数,大家参考使用吧
复制代码 代码如下:
/**
* 因为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();
}
相关文章
使用Springboot打成jar包thymeleaf的问题
这篇文章主要介绍了使用Springboot打成jar包thymeleaf的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-11-11
MybatisPlus更新为null的字段及自定义sql注入
mybatis-plus在执行更新操作,当更新字段为空字符串或者null的则不会执行更新,本文主要介绍了MybatisPlus更新为null的字段及自定义sql注入,感兴趣的可以了解一下2024-05-05
Java SpringBoot集成文件之如何使用POI导出Word文档
这篇文章主要介绍了Java SpringBoot集成文件之如何使用POI导出Word文档,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的朋友可以参考一下2022-08-08


最新评论