您的位置:首页 > 理论基础 > 计算机网络

Android的Http网络请求模型初步

2012-07-31 14:56 441 查看
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: