Http异步下载xml和json文件

作者:追风剑情 发布于:2015-8-10 21:49 分类:Android

package com.example.androidtest;

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

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class NetworkingActivity1 extends Activity {
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_networking);
		
		String url = "http://www.devacg.com/test/test.xml";
		new DownloadTextTask().execute(url);
	}
	
	private InputStream OpenHttpConnection(String urlString) throws IOException
	{
		InputStream in = null;
		int response = -1;
		
		URL url = new URL(urlString);
		URLConnection conn = url.openConnection();
		
		if(!(conn instanceof HttpURLConnection))
			throw new IOException("Not an HTTP connection");
		
		try {
			HttpURLConnection httpConn = (HttpURLConnection) conn;
			httpConn.setAllowUserInteraction(false);
			httpConn.setInstanceFollowRedirects(true);
			httpConn.setRequestMethod("GET");
			httpConn.connect();
			response = httpConn.getResponseCode();
			if(response == HttpURLConnection.HTTP_OK){
				in = httpConn.getInputStream();
			}
		} catch (Exception ex) {
			Log.d("AndroidTest", ex.getLocalizedMessage());
			throw new IOException("Error connecting");
		}
		
		return in;
	}
	
	/**
	 * 下载xml文件
	 * @param url
	 */
	private void DownloadXML(String url)
	{
		InputStream in = null;
		try {
			in = OpenHttpConnection("http://www.devacg.com/test/test.xml");
			Document doc = null;
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db;
			db = dbf.newDocumentBuilder();
			doc = db.parse(in);
			doc.getDocumentElement().normalize();
			//TODO:: 以下根据xml的结构进行具体解析
			
		}catch(ParserConfigurationException e){
			Log.d("AndroidTest", e.getLocalizedMessage());
		}catch(Exception e){
			Log.d("AndroidTest", e.getLocalizedMessage());
		}
	}
	
	/**
	 * 下载json文件
	 * @param url	json文件url地址
	 * @return
	 */
	private String DownloadJSON(String url)
	{
		StringBuilder stringBuilder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		try {
			HttpResponse response = client.execute(httpGet);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if(statusCode == 200){
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(content));
				String line;
				while((line = reader.readLine()) != null){
					stringBuilder.append(line);
				}
			}else{
				Log.e("AndroidTest", "Failed to download file");
			}
		}catch(ClientProtocolException e){
			Log.d("AndroidTest", e.getLocalizedMessage());
		}catch(IOException e){
			Log.d("AndroidTest", e.getLocalizedMessage());
		}
		return stringBuilder.toString();
	}
	
	private String DownloadText(String url)
	{
		int BUFFER_SIZE = 2000;
		InputStream in = null;
		try {
			in = OpenHttpConnection(url);
		} catch (IOException e) {
			Log.d("AndroidTest", e.getLocalizedMessage());
			return "";
		}
		
		InputStreamReader isr = new InputStreamReader(in);
		int charRead;
		String str = "";
		char[] inputBuffer = new char[BUFFER_SIZE];
		try {
			while((charRead = isr.read(inputBuffer)) > 0) {
				String readString = String.copyValueOf(inputBuffer, 0, charRead);
				str += readString;
				Log.d("AndroidTest", str);
				inputBuffer = new char[BUFFER_SIZE];
			}
			in.close();
		} catch (IOException e) {
			Log.d("AndroidTest", e.getLocalizedMessage());
			return "";
		}
		return str;
	}
	
	
	private class DownloadTextTask extends AsyncTask<String, Void, String>
	{
		protected String doInBackground(String... urls){
			return DownloadText(urls[0]);
		}
		
		protected void onPostExecute(String result){
			Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
		}
	}
}

标签: Android

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号