Android的Http网络请求模型初步

Android系统默认支持两种方式进行网络通信,来自Apache的HttpClient和Java自身的HttpURLConnection,官方文档显示自从GingerBread版本即2.3开始推荐使用HttpURLConnection,因为它代码更精简,bug也更少,但在之前版本有一些bug

	private HttpClient httpClient;
	private HttpEntity httpEntity;
	private HttpResponse httpResponse;
	private HttpPost httpPost;

	private static final int TIMEOUT = 10000;
	private static final String TAG = "HttpManager";

	public int doPost(String url, Map<String, String> map)
	{
		try
		{
			httpClient = new DefaultHttpClient();
			httpPost = new HttpPost(url);
			//将map对象转成json格式,再转成String类型
			JSONObject json = new JSONObject(map);
			httpEntity = new StringEntity(json.toString(), HTTP.ISO_8859_1);
			Log.d(TAG, "json: " + json);
			httpPost.setEntity(httpEntity);
			httpResponse = httpClient.execute(httpPost);
			int code = httpResponse.getStatusLine().getStatusCode();
			Log.d(TAG, "code: " + code);
			HttpEntity entity = httpResponse.getEntity();
			StringBuilder builder = new StringBuilder();
			BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), HTTP.UTF_8));
			String s;
			while ((s = reader.readLine()) != null)
			{
				builder.append(s);
			}
			int result = Integer.parseInt(builder.toString());
			Log.d(TAG, "result: " + result);
			return result;
		} catch (Exception e)
		{
			return -1;
		}
	}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值