android 遠程訪問tomcat工程中的xml

String xml=downloadXMl("url/文件.xml");

調用方法:
private String downloadXMl(String urlStr){
  	    HttpDownloader httpDownloader=new HttpDownloader();
  	    String result=httpDownloader.download(urlStr);
  	    return result;   
  	}
public class HttpDownloader {

	/**
	 * 根據URL下載文件,前提是這個文件當中的內容是文本,函數的返回值就是文件當中的內容
	 * 1.創建一個URL對象
	 * 2.通過URL對象,創建一個HttpURLConnection對象
	 * 3.得到InputStram
	 * 4.從InputStream當中讀取數據
	 * @param urlStr
	 * @return
	 */
	public String download(String urlStr) {
		StringBuffer sb = new StringBuffer();
		String line = null;
		BufferedReader buffer = null;
		try {
			// 創建一個URL對象
			URL url = new URL(urlStr);
			// 創建一個Http連接
			HttpURLConnection urlConn = (HttpURLConnection) url
					.openConnection();
			// 使用IO流讀取數據
			buffer = new BufferedReader(new InputStreamReader(urlConn
					.getInputStream(),"utf-8"));
			while ((line = buffer.readLine()) != null) {
				sb.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				buffer.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
}






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章