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

被折叠的 条评论
为什么被折叠?



