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;
}
}