处理HTTP请求并返回JSON数据的类

这里实现了HTTP请求的发送并获取返回JSON格式的数据(实际上能够返回任意的文本数据,例如XML),能够处理POST和GET请求类型:

源码文件:

package com.freesoft.utils.network;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;

import android.os.Handler;
import android.os.Message;

public class HttpUtil {
	private enum Method {
		post, get
	};

	private WorkingThread t = null;

	/**
	 * send get request
	 * @param urlString
	 * @param paramMap
	 * @param handler
	 * @param msgId
	 */
	public void sendGetRequest(String urlString, Map<String, String> paramMap, Handler handler, int msgId) {
		t = new WorkingThread(handler, urlString, paramMap, msgId, Method.get);
		t.start();
	}
	
	/**
	 * send post request
	 * @param urlString
	 * @param paramMap
	 * @param handler
	 * @param msgId
	 */
	public void sendPostRequest(String urlString, Map<String, String> paramMap, Handler handler, int msgId) {
		t = new WorkingThread(handler, urlString, paramMap, msgId, Method.post);
		t.start();
	}

	public String getData() {
		return t.getData();
	}

	class WorkingThread extends Thread {
		public static final int BUF_SIZE = 4096;
		private Handler handler = null;
		private String urlString = null;
		private int msgId = -1;
		private Map<String, String> paramMap = null;
		private String data = "";

		private Method method;

		public String getData() {
			return data;
		}

		public WorkingThread(Handler handler, String urlString,
				Map<String, String> paramMap, int msgId, Method method) {
			this.handler = handler;
			this.urlString = urlString;
			this.paramMap = paramMap;
			this.msgId = msgId;

			this.method = method;
		}

		@Override
		public void run() {
			URL url = null;
			HttpURLConnection conn = null;
			try {
				url = new URL(urlString);
				conn = (HttpURLConnection) url.openConnection();
				if (method == Method.get)
					getGetData(conn);
				else
					getPostData(conn);

				Message msg = handler.obtainMessage(msgId);
				handler.sendMessage(msg);
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				conn.disconnect();
			}
			super.run();
		}

		/**
		 * get response data from request(POST method)
		 * @param conn
		 * @throws IOException
		 */
		private void getPostData(HttpURLConnection conn) throws IOException {
			// setup for post method
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setRequestMethod("POST");
			conn.setUseCaches(false);
			conn.setInstanceFollowRedirects(true);
			conn.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			conn.connect();

			// if parameter list is not empty, we must commit (encode is utf-8) 
			if ((paramMap != null) && (!paramMap.isEmpty())) {
				DataOutputStream out = new DataOutputStream(
						conn.getOutputStream());
				String paramString = "";
				for(Iterator<String> iter = paramMap.keySet().iterator(); iter.hasNext();) {
					String param = iter.next();
					String value = URLEncoder.encode(paramMap.get(param), "utf-8");
					paramString += (param + "=" + value);
					if (iter.hasNext())
						paramString += "&";
				}
				out.writeBytes(paramString);
				out.flush();
				out.close();
			}

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			String inputLine = "";
			while ((inputLine = reader.readLine()) != null) {
				data += inputLine;
			}
			reader.close();
		}

		/**
		 * get response data from request(GET method)
		 * @param conn
		 * @throws ProtocolException
		 * @throws IOException
		 */
		private void getGetData(HttpURLConnection conn)
				throws ProtocolException, IOException {
			conn.setReadTimeout(5 * 1000);
			conn.setRequestMethod("GET");

			int code = conn.getResponseCode();
			if (code != 200)
				throw new RuntimeException("request failed");

			InputStream in = conn.getInputStream();
			readStream(in);
			in.close();
		}

		/**
		 * Read Input Stream
		 * @param in
		 */
		private void readStream(InputStream in) {
			char[] buf = new char[BUF_SIZE];
			int size = 0;
			data = new String();
			InputStreamReader reader = new InputStreamReader(in);
			try {
				while ((size = reader.read(buf, 0, BUF_SIZE)) > 0) {
					data = data + String.copyValueOf(buf, 0, size);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}



测试代码,具体测试链接地址请自行更新:

package com.freesoft.androidtest;

import java.util.HashMap;
import java.util.Map;

import com.freesoft.utils.network.HttpUtil;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

@SuppressLint("HandlerLeak")
public class MainActivity extends Activity {
	private static final int MSG_HTTPDATA = 1;
	
	private Button btnTest = null;
	private TextView tv = null;
	private HttpUtil util = null;
	
	private final String urltest = "http://www.sina.com.cn";
	
	private Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_HTTPDATA:
				tv.setText(util.getData());
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
		
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		initUI();
	}

	private void initUI() {
		tv = (TextView) findViewById(R.id.main_testtv);
		btnTest = (Button) findViewById(R.id.main_testbtn);
		btnTest.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				util = new HttpUtil();
				Map<String, String> paramMap = new HashMap<String, String>();
				paramMap.put("uid", "1");
				util.sendPostRequest(urltest, paramMap, handler, MSG_HTTPDATA);
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值