android联网程序,android 联网 HttpClient

可以使用 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;

}

}

0818b9ca8b590ca3270a3433284dd417.png注:

0818b9ca8b590ca3270a3433284dd417.png

0818b9ca8b590ca3270a3433284dd417.png  1.    使用POST方式时,传递参数必须使用NameValuePair数组

2.    使用GET方式时,通过URL传递参数,注意写法

3.    通过setEntity方法来发送HTTP请求

4.    通过DefaultHttpClient 的 execute方法来获取HttpResponse

5.    通过getEntity()从Response中获取内容

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值