FileUtils扩展readURLtoString读取url内容
程序员文章站
2024-02-17 16:44:40
复制代码 代码如下:/** * 因为fileutils不支持,所以添加个方法 string content = * fileutils.readfi...
复制代码 代码如下:
/**
* 因为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();
}