android 数据上传

本文介绍了在Android应用开发中如何实现数据上传,包括用户反馈、操作习惯等信息的上传,使用了org.apache.http包的API进行实现,通过示例代码详细展示了数据上传的过程。

        在Android开发过程中,我们时常要上传数据,比如用户反馈的信息,调查用户的操作习惯,或则在播放器中上传些视频播放信息等等。我们可以运用org.apache.http包中API来上传数据,直接看代码:

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.util.Log;

public class UploadDatas
{
	public static boolean post(String url, String json)
	{
		boolean flag = false;
		/**
		 * url:上传到服务器的url地址 json:上传的json字符串, 当然可以上传其他的数据类型,只需在服务器端解析相应的数据格式
		 */
		try
		{
			/**
			 * 创建POST请求对象 也可以使用GET方式请求,在此只用POST演示
			 */
			HttpPost httpRequest = new HttpPost(url);
			/**
			 * 将请求字符串转化为请求实体 将请求实体放在请求对象中
			 */
			httpRequest.setEntity(new StringEntity(json, "utf-8"));
			/**
			 * 创建HttpClient对象 HttpClient对象用于发送请求
			 */
			HttpClient httpClient = new DefaultHttpClient();
			/**
			 * 执行请求对象 返回服务器响应对象
			 */
			HttpResponse httpResponse = httpClient.execute(httpRequest);

			/*
			 * HttpResponse httpResponse = new DefaultHttpClient()
			 * .execute(httpRequest);
			 */

			/**
			 * 检查响应状态是否正常:检查状态码的值是200表示正常
			 */
			if (httpResponse.getStatusLine().getStatusCode() == 200)
			{
				flag = true;

				String strResult = EntityUtils.toString(httpResponse
						.getEntity());

				Log.d("upload", json + "  status:" + strResult);
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return flag;
	}

	// GET请求方式上传
	/*public void get(String url, String data)
	{
		HttpClient httpClient = new DefaultHttpClient();
		String getUrl = url + "parameter=" + data;
		HttpGet httpGet = new HttpGet(getUrl);
		try
		{
			HttpResponse response = httpClient.execute(httpGet);
			if (response.getStatusLine().getStatusCode() == 200)
			{
				HttpEntity entity = response.getEntity();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(entity.getContent()));
				String result = reader.readLine();
				Log.d("HTTP", "GET:" + result);
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}*/

}


        OK,数据上传搞定^_^...^_^

        

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值