可以使用 Android 集成进来的 apache 中关于联网的API。
HttpParams : 保存Http请求设定的参数对象
HttpConnectionParams :提供对Http连接参数进行设定的方法,比如 连接超时时间 等。
HttpClient :发起Http连接请求的对象,
HttpResponse :Http 请求返回的响应
最后,其实apache还是提供了释放 连接资源的方法的,不过是埋得深了点。
httpClient.getConnectionManager().shutdown();
这个shutdown并不是将手机网络断掉,而是将建立Http连接请求时所分配的资源释放掉
工具类
/*
* post请求
*/
public static String post(RequestVo vo){
//使用DefaultHttpClient创建HttpClient实例
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(vo.context.getString(R.string.host).concat(vo.context.getString(vo.requestUrl)));
//构建HttpPost
HttpParams params = new BasicHttpParams();//
params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 20000); //连接超时
HttpConnectionParams.setSoTimeout(params, 30*1000); //响应超时
post.setParams(params);
String str = null;
/** 保持会话Session **/
/** 设置Cookie **/
MyHttpCookies li = new MyHttpCookies(vo.context);
CookieStore cs = li.getuCookie();
/** 第一次请求App保存的Cookie为空,所以什么也不做,只有当APP的Cookie不为空的时。把请请求的Cooke放进去 **/
if (cs != null) {
client.setCookieStore(li.getuCookie());
System.out.println("session");
}
/** 保持会话Session end **/
try {
//将由Map存储的参数转化为键值参数
if(vo.requestDataMap!=null){
HashMap map = vo.requestDataMap;
ArrayList pairList = new ArrayList();
for(Map.Entry entry:map.entrySet()){
BasicNameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
pairList.add(pair);
}
//使用编码构建Post实体
HttpEntity entity = new UrlEncodedFormEntity(pairList,"UTF-8");
//设置Post实体
post.setEntity(entity);
}
//执行Post方法
HttpResponse response = client.execute(post);//包含响应的状态和返回的结果==
if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
//获取Cookie
li.setuCookie(client.getCookieStore());
//获取返回实体
String result = EntityUtils.toString(response.getEntity(),"UTF-8");
Log.e(NetUtil.class.getSimpleName(), result);
try {
str = result;
} catch (Exception e) {
Log.e(NetUtil.class.getSimpleName(), e.getLocalizedMessage(),e);
}
return str;
}
} catch (ClientProtocolException e) {
Log.e(NetUtil.class.getSimpleName(), e.getLocalizedMessage(),e);
return null;
} catch (IOException e) {
Log.e(NetUtil.class.getSimpleName(), e.getLocalizedMessage(),e);
return null;
}
return null;
}
/**
* get请求
* @param vo
* @return
*/
public static String get(RequestVo vo, String url){
DefaultHttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
String str = null;
/** 保持会话Session **/
// /** 设置Cookie **/
MyHttpCookies li = new MyHttpCookies(vo.context);
CookieStore cs = li.getuCookie();
/** 第一次请求App保存的Cookie为空,所以什么也不做,只有当APP的Cookie不为空的时。把请请求的Cooke放进去 **/
if (cs != null) {
client.setCookieStore(li.getuCookie());
System.out.println("session");
}
// /** 保持会话Session end **/
try {
HttpResponse response = client.execute(get);
if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
li.setuCookie(client.getCookieStore());
String result = EntityUtils.toString(response.getEntity(),"UTF-8");
Log.e(NetUtil.class.getSimpleName(), result);
try {
str = result;
} catch (Exception e) {
Log.e(NetUtil.class.getSimpleName(), e.getLocalizedMessage(),e);
}
return str;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* http请求的缓存和一些公用的参数
* @author llc
*
*/
public class MyHttpCookies {
/** 每页数据显示最大数 */
private static int pageSize = 10;
/** 当前会话后的cokie信息 */
private static CookieStore uCookie = null;
/** 公用的HTTP提示头信息 */
private static Header[] httpHeader;
/** HTTP连接的网络节点 */
private static String httpProxyStr;
/**http请求的公用url部分**/
public static String baseurl = "http://www.2cto.com /River";
/**上下文对象**/
Context context;
public MyHttpCookies(Context context){
this.context = context;
/** y设置请求头 **/
/** y设置请求头 **/
// Header[] header = {
// new BasicHeader("PagingRows", String.valueOf(pageSize)) };
// httpHeader = header;
}
/**
* 增加自动选择网络,自适应cmwap、CMNET、wifi或3G
*/
@SuppressWarnings("static-access")
public void initHTTPProxy() {
WifiManager wifiManager = (WifiManager) (context.getSystemService(context.WIFI_SERVICE));
if (!wifiManager.isWifiEnabled()) {
Uri uri = Uri.parse("content://telephony/carriers/preferapn"); // 获取当前正在使用的APN接入点
Cursor mCursor =context. getContentResolver().query(uri, null, null, null,
null);
if (mCursor != null) {
mCursor.moveToNext(); // 游标移至第一条记录,当然也只有一条
httpProxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
}
} else {
httpProxyStr = null;
}
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public CookieStore getuCookie() {
return uCookie;
}
public void setuCookie(CookieStore uCookie) {
this.uCookie = uCookie;
}
public Header[] getHttpHeader() {
return httpHeader;
}
public String getHttpProxyStr() {
return httpProxyStr;
}
}
注:
1. 使用POST方式时,传递参数必须使用NameValuePair数组
2. 使用GET方式时,通过URL传递参数,注意写法
3. 通过setEntity方法来发送HTTP请求
4. 通过DefaultHttpClient 的 execute方法来获取HttpResponse
5. 通过getEntity()从Response中获取内容