FileUtils擴大readURLtoString讀取url內容。本站提示廣大學習愛好者:(FileUtils擴大readURLtoString讀取url內容)文章只能為提供參考,不一定能成為您想要的結果。以下是FileUtils擴大readURLtoString讀取url內容正文
/**
* 由於FileUtils不支撐,所以添加個辦法 String content =
* FileUtils.readFileToString(FileUtils.toFile(new
* URL("http://www.百度.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.百度.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();
}