---
title: "处女apk纠结过的技术点<1>"
author: "ping8080"
date: "2011-02-24T10:46:56Z"
tags: []
categories: ["移动开发"]
slug: "apk-1"
draft: false
lastmod: "2011-02-28T11:37:38Z"
id: 921031
url: "https://ping8080.iteye.com/blog/921031"
---

网络链接访问为题  
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;  
  }     
 }