码迷,mamicode.com
首页 > 移动开发 > 详细

Android网络连接工具最佳优化

时间:2015-01-27 11:19:05      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:javabean   webview   json   socket   class   

package com.jia.httputiltools;

public interface HttpCallbackListener {

	void onFinish(String response);

	void onError(Exception e);
}

package com.jia.httputiltools;

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

/**
 * @author 姚文天
 * 
 */
public class HttpUtil {
	public static void sendHttpRequest(final String address,
			final HttpCallbackListener listener) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				HttpURLConnection connection = null;
				try {
					URL url = new URL(address);
					connection = (HttpURLConnection) url.openConnection();
					connection.setRequestMethod("GET");
					connection.setConnectTimeout(8000);
					connection.setReadTimeout(8000);
					connection.setDoInput(true);
					connection.setDoOutput(true);
					InputStream in = connection.getInputStream();
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(in));
					StringBuilder response = new StringBuilder();
					String line;
					while ((line = reader.readLine()) != null) {
						response.append(line);
					}
					if (listener != null) {
						// 回调onFinish()方法
						listener.onFinish(response.toString());
					}
				} catch (Exception e) {
					if (listener != null) {
						// 回调onError()方法
						listener.onError(e);
					}
				} finally {
					if (connection != null) {
						connection.disconnect();
					}
				}

			}
		}).start();

	}
}

package com.jia.httputiltools;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {
	String address = "http://blog.csdn.net/fang323619";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
			@Override
			public void onFinish(String response) {
				// 在这里根据返回内容执行具体的逻辑
			}

			@Override
			public void onError(Exception e) {
				// 在这里对异常情况进行处理
			}
		});
	}
}

Android网络连接工具最佳优化

标签:javabean   webview   json   socket   class   

原文地址:http://blog.csdn.net/fang323619/article/details/43191115

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!