原创, 安卓

Android 获取网络信息html,xml,json等信息

我这里写了一个类,方便使用android获取网页内容,无论是html,xml,json还是其他,只是原样获得,想要内容,需要自己再去解析,其实就是将网页内容转成2进制在转回来,个人实现方法如下


package com.windigniter.transport;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class HttpDownloader {
	private URL url = null;
	/**
	 * download file from url address, 
	 * 1.create URL object
	 * 2.Create HttpURLCommection object from this URL object
	 * 3.get InputStream
	 * 4.get data from InputStream
	 */
	public HttpDownloader() {
		
	}
	public String getHttpContents(String urlStr){
		StringBuffer sb = new StringBuffer();
		String line = null;
		BufferedReader buffer = null;
		try{
			//System.out.println("HttpDownloader-->download-->urlStr --->" + urlStr);
			InputStream inputStream = getInputStreamFromUrl(urlStr);
			if(inputStream != null){
				//System.out.println("HttpDownloader-->download-->inputStream22 --->" + inputStream);
				buffer = new BufferedReader(new InputStreamReader(inputStream));
				while((line = buffer.readLine()) != null){
					sb.append(line);
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try{
				buffer.close();
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		//System.out.println("HttpDownloader-->download-->inputStream33 --->" + sb.toString());
		return sb.toString();
	}
	
	public InputStream getInputStreamFromUrl(String urlStr) throws MalformedURLException,IOException{
		//create URL object
		url = new URL(urlStr);
		InputStream inputStream = null;
		//create http connection
		HttpURLConnection urlConn = null;
		if(url.openConnection().getContentType() != null){
			try{
				urlConn = (HttpURLConnection) url.openConnection();
				//System.out.println("HttpDownloader-->getInputStreamFromUrl-->getResponseCode --->" + urlConn.getResponseCode());
				if(urlConn.getResponseCode() == HttpURLConnection.HTTP_OK){
					inputStream  = urlConn.getInputStream();
					//System.out.println("HttpDownloader-->getInputStreamFromUrl-->inputStream --->" + inputStream);				
				}
			}catch(Exception e){
				//System.out.println("HttpDownloader-->getInputStreamFromUrl-->Status --->" + urlConn.getResponseCode());
				e.printStackTrace();
			}	
		}
		return inputStream;
	}
}

这段代码已经将异常等信息都处理了,个人一直在使用的一个类,现在把他分享出来。

(1358)

Author Since: Jul 05, 2018

Related Post