Http异步下载文本

作者:追风剑情 发布于:2015-8-6 22:42 分类:Android

活动

package com.example.androidtest;

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 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;
	}
	
	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();
		}
	}
}

运行效果

text.png

标签: Android

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号