android-sdk集成了多种网络编程的包,Apache的HttpClient来方便我们使用各种Http服务。个人觉得可以把HttpClient想象成一个浏览器,通过它的API我们可以很方便的发出GET,POST请求,在3G和wifi 的环境下,无需做过多的处理,但是在wap环境(cmwap,uniwap,ctwap)下,必须设置代理。具体的代码整理如下:
HttpClient -post方式:
public static Object httpClientpost(RequestVo reqVo){
DefaultHttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost(reqVo.requestUrl);
//post.setHeaders(headers);
HttpParams params = client.getParams();
//连接超时 时间
params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 6000);
//读取数据超时 时间
params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 6000);
//如果在cmwap uniwap ctwap环境就要设置代理
HttpHost host=new HttpHost(Proxy.getDefaultHost(), Proxy.getDefaultPort());
params.setParameter(ConnRouteParams.DEFAULT_PROXY, post);
Object obj=null;
try {
if(reqVo.requestDataMap!=null&&!reqVo.requestDataMap.isEmpty()){
HashMap<String, String> requestDataMap = reqVo.requestDataMap;
ArrayList<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
for(Entry<String, String> map: requestDataMap.entrySet() ){
pairList.add(new BasicNameValuePair(map.getKey(), map.getValue()));
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairList,"UTF-8");
post.setEntity(entity);
}
HttpResponse response = client.execute(post);
if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
String result = EntityUtils.toString(response.getEntity());
obj = reqVo.jsonParser.parseJSON(result);
}
} catch (ClientProtocolException e) {
Log.i(NetUtil.class.getSimpleName(), e.getMessage(), e);
} catch (IOException e) {
Log.i(NetUtil.class.getSimpleName(), e.getMessage(), e);
} catch (JSONException e) {
Log.i(NetUtil.class.getSimpleName(), e.getMessage(), e);
}
return obj;
}
HttpClient-get方式:
public static Object httpClientget(RequestVo reqVo){
DefaultHttpClient client=new DefaultHttpClient();
HttpGet get=new HttpGet(reqVo.requestUrl);
//这里可以设一些参数,比如做app推广统计,或者访问量的统计android ios
// get.setHeaders(headers);
Object obj = null;
try {
HttpResponse response = client.execute(get);
if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
String result = EntityUtils.toString(response.getEntity());
obj = reqVo.jsonParser.parseJSON(result);
}
} catch (ClientProtocolException e) {
Log.i(NetUtil.class.getSimpleName(), e.getMessage(), e);
} catch (IOException e) {
Log.i(NetUtil.class.getSimpleName(), e.getMessage(), e);
} catch (JSONException e) {
Log.i(NetUtil.class.getSimpleName(), e.getMessage(), e);
}
return obj;
}