处女apk纠结过的技术点<1>

                              网络链接访问为题
android url访问主要分为两种:一种是httpurlconnection,另一种是httpclient,而前者只是简单的访问,不能设置参数,头文件等,而后者刚好弥补了前者的不足:

 /**
  * 执行一个HTTP GET请求,返回请求响应的HTML
  *
  * @param url
  *            请求的URL地址
  * @param queryString
  *            请求的查询参数,可以为null
  * @param charset
  *            字符集
  * @param pretty
  *            是否美化
  * @return 返回请求响应的HTML
  */
 public static String doGetHttpHTML(String url, String cookie) {
  StringBuffer response = new StringBuffer();
  DefaultHttpClient client = new DefaultHttpClient(); 
  HttpGet method = new HttpGet(url);
  // 设置Http header数据
  if(cookie != null){ 
   String sessionId=StringUtils.cookieHandle(cookie.toString());
   method.setHeader("Cookie",sessionId);   
  }  
  try {   
   
   HttpResponse res=client.execute(method);
   if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
    HttpEntity entity=res.getEntity();
    BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));    
    String line;
    while ((line = reader.readLine()) != null) {     
     response.append(line).append(System.getProperty("line.separator"));    
    }
    reader.close();
   }
   return response.toString();
  } catch(IOException e) {
   Log.i("执行HTTP Get请求" + url + "时,发生异常!", e.toString());
   return "InternetFail";
  } finally {
   client.getConnectionManager().shutdown();
  } 
 }

 

 

以上获取返回值和httpurlconnection 功能差不多  ,一下这段代码获取cookie

 /**
  * 获取登陆Cookie 
  * @param urlpath
  * @return
  * @throws Exception
  */
 public static String getData(String url){  
  DefaultHttpClient httpclient = new DefaultHttpClient();   
  HttpGet httpget = new HttpGet(url);  
  try {
   HttpResponse response = httpclient.execute(httpget);
   CookieStore cookie=httpclient.getCookieStore();
   return cookie.toString();
  } catch (ClientProtocolException e) {   
   e.printStackTrace();
   return null;
  } catch (IOException e) {   
   e.printStackTrace();
   return null;
  }   
 }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值