您的位置:首页 > 移动开发 > Android开发

android获取网页数据的方法

2016-06-01 13:01 387 查看
 1.android获取网页数据的方法:

//第一种
/**获取参数(ArrayList<NameValuePair> nameValuePairs,String url)后post给远程服务器
* 将获得的返回结果(String)返回给调用者
* 本函数适用于查询数量较少的时候
*/
public String posturl(ArrayList<NameValuePair> nameValuePairs,String url){
    String result = "";
    String tmp= "";
    InputStream is = null;
    try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
    }catch(Exception e){
        return "Fail to establish http connection!";
    }

    try{
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();

        tmp=sb.toString();
    }catch(Exception e){
        return "Fail to convert net stream!";
    }

    try{
        JSONArray jArray = new JSONArray(tmp);
        for(int i=0;i<jArray.length();i++){
            JSONObject json_data = jArray.getJSONObject(i);
            Iterator<?> keys=json_data.keys();
            while(keys.hasNext()){
                result += json_data.getString(keys.next().toString());
            }
        }
    }catch(JSONException e){
        return "The URL you post is wrong!";
    }

    return result;
}

//第二种
/**获取参数指定的网页代码,将其返回给调用者,由调用者对其解析
* 返回String
*/
public String posturl(String url){
    InputStream is = null;
    String result = "";

    try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
    }catch(Exception e){
        return "Fail to establish http connection!"+e.toString();
    }

    try{
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();

        result=sb.toString();
    }catch(Exception e){
        return "Fail to convert net stream!";
    }

    return result;
}

//第三种
/**获取指定地址的网页数据
* 返回数据流
*/
public InputStream streampost(String remote_addr){
    URL infoUrl = null;
    InputStream inStream = null;
    try {
        infoUrl = new URL(remote_addr);
        URLConnection connection = infoUrl.openConnection();
        HttpURLConnection httpConnection = (HttpURLConnection)connection;
        int responseCode = httpConnection.getResponseCode();
        if(responseCode == HttpURLConnection.HTTP_OK){
            inStream = httpConnection.getInputStream();
        }
    } catch (MalformedURLException e) {                       
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return inStream;

   2.Android中手机震动的设置(Vibrator)的步骤:

a、通过系统服务获得手机震动服务,Vibrator vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);  

b、得到震动服务后检测vibrator是否存在:

vibrator.hasVibrator();

检测当前硬件是否有vibrator,如果有返回true,如果没有返回false。

c、根据实际需要进行适当的调用,

vibrator.vibrate(long milliseconds);

开始启动vibrator持续milliseconds毫秒。     

vibrator.vibrate(long[] pattern, int repeat);

以pattern方式重复repeat次启动vibrator。(pattern的形式为new  long[]{arg1,arg2,arg3,arg4......},其中以两个一组的如arg1 和arg2为一组、arg3和arg4为一组,每一组的前一个代表等待多少毫 秒启动vibrator,后一个代表vibrator持续多少毫秒停止,之后往复即 可。Repeat表示重复次数,当其为-1时,表示不重复只以pattern的方 式运行一次)。

vibrator.cancel();

Vibrator停止。

http://www.apkbus.com/android-1807-1-1.html

3.Android如何使用读写cookie的方法

可以使用SharedPreferences或者SQLite来保存用户信息
private static HashMap<String,String>  CookieContiner=new HashMap<String,String>() ;
    /**
     * 保存Cookie
     * @param resp
     */
    public void SaveCookies(HttpResponse httpResponse)
    {
        Header[] headers = httpResponse.getHeaders("Set-Cookie");
        String headerstr=headers.toString();
        if (headers == null)
            return;

        for(int i=0;i<headers.length;i++)
        {
            String cookie=headers[i].getValue();
            String[]cookievalues=cookie.split(";");
            for(int j=0;j<cookievalues.length;j++)
            {
                String[] keyPair=cookievalues[j].split("=");
                String key=keyPair[0].trim();
                String value=keyPair.length>1?keyPair[1].trim():"";
                CookieContiner.put(key, value);
            }
        }
    }
    /**
     * 增加Cookie
     * @param request
     */
    public void AddCookies(HttpPost request)
    {
        StringBuilder sb = new StringBuilder();
        Iterator iter = CookieContiner.entrySet().iterator();
        while (iter.hasNext()) {
          Map.Entry entry = (Map.Entry) iter.next();
          String key = entry.getKey().toString();
          String val = entry.getValue().toString();
          sb.append(key);
          sb.append("=");
          sb.append(val);
          sb.append(";");
        }
        request.addHeader("cookie", sb.toString());
    } 
做了一个android网络应用,要求用自己实现的webview去访问web网站,并且在远程登录成功之后把cookie写入到手机,保留用作以后的自动登录。找了好多资料。发觉读取cookies倒还用的很普遍,可是通过程序写cookie却没有太多资料。

先来看一下如何读取cookie吧:

try
        {
          DefaultHttpClient httpclient = new DefaultHttpClient();
          HttpGet httpget = new HttpGet("http://www.hlovey.com/");
          HttpResponse response = httpclient.execute(httpget);
          HttpEntity entity = response.getEntity();
          List<Cookie> cookies = httpclient.getCookieStore().getCookies();
          if (entity != null) {
              entity.consumeContent();
          }

          if (cookies.isEmpty()) {
            Log.i(TAG, "NONE");
         } else {
             for (int i = 0; i < cookies.size(); i++) {             
               Log.i(TAG,"- domain " + cookies.get(i).getDomain());
               Log.i(TAG,"- path " + cookies.get(i).getPath());
               Log.i(TAG,"- value " + cookies.get(i).getValue());
               Log.i(TAG,"- name " + cookies.get(i).getName());
               Log.i(TAG,"- port " + cookies.get(i).getPorts());
               Log.i(TAG,"- comment " + cookies.get(i).getComment());
               Log.i(TAG,"- commenturl" + cookies.get(i).getCommentURL());
               Log.i(TAG,"- all " + cookies.get(i).toString());
             }
         }
          httpclient.getConnectionManager().shutdown();

        }catch(Exception e){
          //Todo
        }finally{
        //Todo         
        }
通过分析com.android.browser的源码,发现android默认的browser增加cookie是在数据库中增加记录,和window不同,win是采用一个txt文本文件的形式来存储cookie。而android是将cookie存储在数据库中。具体的介绍在《android cookie存储位置》一文中有介绍。我们都知道,android每个应用程序的存储空间都是独立的。不管使用preference还是database存储,都会在每个/data/data/package name/下面进行存储(preference存储在/data/data/package name/shared_prefs/xxxx.xml)。前面也说到cookie是存在数据库中,那么如果采用非浏览器访问网络需要保留cookie的话我们就应该在database中建立cookies表,并且存入相应的cookies数据。仿照默认broswer的代码:

/**声明一些数据库操作的常量*/
  private static SQLiteDatabase mDatabase = null;
  private static final String DATABASE_FILE = "webview.db";
  private static final String COOKIES_NAME_COL = "name";
  private static final String COOKIES_VALUE_COL = "value";
  private static final String COOKIES_DOMAIN_COL = "domain";
  private static final String COOKIES_PATH_COL = "path";
  private static final String COOKIES_EXPIRES_COL = "expires";
  private static final String COOKIES_SECURE_COL = "secure";
mDatabase = LoginApiActivity.this.openOrCreateDatabase(DATABASE_FILE, 0, null);
//创建cookie数据库
    if (mDatabase != null) {
      // cookies
      mDatabase.execSQL("CREATE TABLE IF NOT EXISTS cookies "
              + " (_id INTEGER PRIMARY KEY, "
              + COOKIES_NAME_COL + " TEXT, " + COOKIES_VALUE_COL
              + " TEXT, " + COOKIES_DOMAIN_COL + " TEXT, "
              + COOKIES_PATH_COL + " TEXT, " + COOKIES_EXPIRES_COL
              + " INTEGER, " + COOKIES_SECURE_COL + " INTEGER" + ");");
      mDatabase.execSQL("CREATE INDEX IF NOT EXISTS cookiesIndex ON "
              + "cookies" + " (path)");
    }
  }

/*写cookie*/
  public void addCookie(Cookie cookie) {
    if (cookie.getDomain() == null || cookie.getPath() == null || cookie.getName() == null
            || mDatabase == null) {
        return;
    }
    String mCookieLock = "asd";
    synchronized (mCookieLock) {
        ContentValues cookieVal = new ContentValues();
        cookieVal.put(COOKIES_DOMAIN_COL, cookie.getDomain());
        cookieVal.put(COOKIES_PATH_COL, cookie.getPath());
        cookieVal.put(COOKIES_NAME_COL, cookie.getName());
        cookieVal.put(COOKIES_VALUE_COL, cookie.getValue());

        mDatabase.insert("cookies", null, cookieVal);

    }
}

 1.android获取网页数据的方法:

//第一种
/**获取参数(ArrayList<NameValuePair> nameValuePairs,String url)后post给远程服务器
* 将获得的返回结果(String)返回给调用者
* 本函数适用于查询数量较少的时候
*/
public String posturl(ArrayList<NameValuePair> nameValuePairs,String url){
    String result = "";
    String tmp= "";
    InputStream is = null;
    try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
    }catch(Exception e){
        return "Fail to establish http connection!";
    }

    try{
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();

        tmp=sb.toString();
    }catch(Exception e){
        return "Fail to convert net stream!";
    }

    try{
        JSONArray jArray = new JSONArray(tmp);
        for(int i=0;i<jArray.length();i++){
            JSONObject json_data = jArray.getJSONObject(i);
            Iterator<?> keys=json_data.keys();
            while(keys.hasNext()){
                result += json_data.getString(keys.next().toString());
            }
        }
    }catch(JSONException e){
        return "The URL you post is wrong!";
    }

    return result;
}

//第二种
/**获取参数指定的网页代码,将其返回给调用者,由调用者对其解析
* 返回String
*/
public String posturl(String url){
    InputStream is = null;
    String result = "";

    try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
    }catch(Exception e){
        return "Fail to establish http connection!"+e.toString();
    }

    try{
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();

        result=sb.toString();
    }catch(Exception e){
        return "Fail to convert net stream!";
    }

    return result;
}

//第三种
/**获取指定地址的网页数据
* 返回数据流
*/
public InputStream streampost(String remote_addr){
    URL infoUrl = null;
    InputStream inStream = null;
    try {
        infoUrl = new URL(remote_addr);
        URLConnection connection = infoUrl.openConnection();
        HttpURLConnection httpConnection = (HttpURLConnection)connection;
        int responseCode = httpConnection.getResponseCode();
        if(responseCode == HttpURLConnection.HTTP_OK){
            inStream = httpConnection.getInputStream();
        }
    } catch (MalformedURLException e) {                       
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return inStream;

   2.Android中手机震动的设置(Vibrator)的步骤:

a、通过系统服务获得手机震动服务,Vibrator vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);  

b、得到震动服务后检测vibrator是否存在:

vibrator.hasVibrator();

检测当前硬件是否有vibrator,如果有返回true,如果没有返回false。

c、根据实际需要进行适当的调用,

vibrator.vibrate(long milliseconds);

开始启动vibrator持续milliseconds毫秒。     

vibrator.vibrate(long[] pattern, int repeat);

以pattern方式重复repeat次启动vibrator。(pattern的形式为new  long[]{arg1,arg2,arg3,arg4......},其中以两个一组的如arg1 和arg2为一组、arg3和arg4为一组,每一组的前一个代表等待多少毫 秒启动vibrator,后一个代表vibrator持续多少毫秒停止,之后往复即 可。Repeat表示重复次数,当其为-1时,表示不重复只以pattern的方 式运行一次)。

vibrator.cancel();

Vibrator停止。

http://www.apkbus.com/android-1807-1-1.html

3.Android如何使用读写cookie的方法

可以使用SharedPreferences或者SQLite来保存用户信息
private static HashMap<String,String>  CookieContiner=new HashMap<String,String>() ;
    /**
     * 保存Cookie
     * @param resp
     */
    public void SaveCookies(HttpResponse httpResponse)
    {
        Header[] headers = httpResponse.getHeaders("Set-Cookie");
        String headerstr=headers.toString();
        if (headers == null)
            return;

        for(int i=0;i<headers.length;i++)
        {
            String cookie=headers[i].getValue();
            String[]cookievalues=cookie.split(";");
            for(int j=0;j<cookievalues.length;j++)
            {
                String[] keyPair=cookievalues[j].split("=");
                String key=keyPair[0].trim();
                String value=keyPair.length>1?keyPair[1].trim():"";
                CookieContiner.put(key, value);
            }
        }
    }
    /**
     * 增加Cookie
     * @param request
     */
    public void AddCookies(HttpPost request)
    {
        StringBuilder sb = new StringBuilder();
        Iterator iter = CookieContiner.entrySet().iterator();
        while (iter.hasNext()) {
          Map.Entry entry = (Map.Entry) iter.next();
          String key = entry.getKey().toString();
          String val = entry.getValue().toString();
          sb.append(key);
          sb.append("=");
          sb.append(val);
          sb.append(";");
        }
        request.addHeader("cookie", sb.toString());
    } 
做了一个android网络应用,要求用自己实现的webview去访问web网站,并且在远程登录成功之后把cookie写入到手机,保留用作以后的自动登录。找了好多资料。发觉读取cookies倒还用的很普遍,可是通过程序写cookie却没有太多资料。

先来看一下如何读取cookie吧:

try
        {
          DefaultHttpClient httpclient = new DefaultHttpClient();
          HttpGet httpget = new HttpGet("http://www.hlovey.com/");
          HttpResponse response = httpclient.execute(httpget);
          HttpEntity entity = response.getEntity();
          List<Cookie> cookies = httpclient.getCookieStore().getCookies();
          if (entity != null) {
              entity.consumeContent();
          }

          if (cookies.isEmpty()) {
            Log.i(TAG, "NONE");
         } else {
             for (int i = 0; i < cookies.size(); i++) {             
               Log.i(TAG,"- domain " + cookies.get(i).getDomain());
               Log.i(TAG,"- path " + cookies.get(i).getPath());
               Log.i(TAG,"- value " + cookies.get(i).getValue());
               Log.i(TAG,"- name " + cookies.get(i).getName());
               Log.i(TAG,"- port " + cookies.get(i).getPorts());
               Log.i(TAG,"- comment " + cookies.get(i).getComment());
               Log.i(TAG,"- commenturl" + cookies.get(i).getCommentURL());
               Log.i(TAG,"- all " + cookies.get(i).toString());
             }
         }
          httpclient.getConnectionManager().shutdown();

        }catch(Exception e){
          //Todo
        }finally{
        //Todo         
        }
通过分析com.android.browser的源码,发现android默认的browser增加cookie是在数据库中增加记录,和window不同,win是采用一个txt文本文件的形式来存储cookie。而android是将cookie存储在数据库中。具体的介绍在《android cookie存储位置》一文中有介绍。我们都知道,android每个应用程序的存储空间都是独立的。不管使用preference还是database存储,都会在每个/data/data/package name/下面进行存储(preference存储在/data/data/package name/shared_prefs/xxxx.xml)。前面也说到cookie是存在数据库中,那么如果采用非浏览器访问网络需要保留cookie的话我们就应该在database中建立cookies表,并且存入相应的cookies数据。仿照默认broswer的代码:

/**声明一些数据库操作的常量*/
  private static SQLiteDatabase mDatabase = null;
  private static final String DATABASE_FILE = "webview.db";
  private static final String COOKIES_NAME_COL = "name";
  private static final String COOKIES_VALUE_COL = "value";
  private static final String COOKIES_DOMAIN_COL = "domain";
  private static final String COOKIES_PATH_COL = "path";
  private static final String COOKIES_EXPIRES_COL = "expires";
  private static final String COOKIES_SECURE_COL = "secure";
mDatabase = LoginApiActivity.this.openOrCreateDatabase(DATABASE_FILE, 0, null);
//创建cookie数据库
    if (mDatabase != null) {
      // cookies
      mDatabase.execSQL("CREATE TABLE IF NOT EXISTS cookies "
              + " (_id INTEGER PRIMARY KEY, "
              + COOKIES_NAME_COL + " TEXT, " + COOKIES_VALUE_COL
              + " TEXT, " + COOKIES_DOMAIN_COL + " TEXT, "
              + COOKIES_PATH_COL + " TEXT, " + COOKIES_EXPIRES_COL
              + " INTEGER, " + COOKIES_SECURE_COL + " INTEGER" + ");");
      mDatabase.execSQL("CREATE INDEX IF NOT EXISTS cookiesIndex ON "
              + "cookies" + " (path)");
    }
  }

/*写cookie*/
  public void addCookie(Cookie cookie) {
    if (cookie.getDomain() == null || cookie.getPath() == null || cookie.getName() == null
            || mDatabase == null) {
        return;
    }
    String mCookieLock = "asd";
    synchronized (mCookieLock) {
        ContentValues cookieVal = new ContentValues();
        cookieVal.put(COOKIES_DOMAIN_COL, cookie.getDomain());
        cookieVal.put(COOKIES_PATH_COL, cookie.getPath());
        cookieVal.put(COOKIES_NAME_COL, cookie.getName());
        cookieVal.put(COOKIES_VALUE_COL, cookie.getValue());

        mDatabase.insert("cookies", null, cookieVal);

    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息