鸟语天空
Http异步下载文本
post by:追风剑情 2015-8-6 22:42

活动

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

评论:
发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容