Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android仿人人客戶端(v5.7.1)——通過HTTPS協議的POST方式獲取用戶的基本信息

Android仿人人客戶端(v5.7.1)——通過HTTPS協議的POST方式獲取用戶的基本信息

編輯:關於Android編程

 
一、擴展之前的網絡模塊

      基於Android仿人人客戶端(v5.7.1)——網絡模塊處理的架構這篇進行擴展,添加通過HTTPS協議的POST方式訪問網絡的處理。自定義類(AsyncHttpsPost)讓其繼承AsyncBaseRequest類,代碼如下:

[java]
package com.everyone.android.net; 
 
import java.io.IOException; 
import java.io.InputStream; 
import java.util.ArrayList; 
import java.util.List; 
import java.util.Map; 
 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.message.BasicNameValuePair; 
import org.apache.http.protocol.HTTP; 
 
import com.everyone.android.callback.ParseCallback; 
import com.everyone.android.callback.ResultCallback; 
 
/**
 * 功能描述:通過HTTPS協議發送POST網絡請求
 * @author android_ls
 *
 */ 
public class AsyncHttpsPost extends AsyncBaseRequest { 
 
    /**
     * 
     */ 
    private static final long serialVersionUID = 4L; 
 
    public AsyncHttpsPost(String url, Map<String, String> parameter, 
            ParseCallback handler, ResultCallback requestCallback) { 
        super(url, parameter, handler, requestCallback); 
    } 
 
    @Override 
    protected InputStream getRequestResult() throws IOException { 
        List<NameValuePair> paramPairs = new ArrayList<NameValuePair>(); 
        if(parameter != null && !parameter.isEmpty()){ 
            for(Map.Entry<String, String> entry : parameter.entrySet()){ 
                paramPairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); 
            } 
        } 
         
        UrlEncodedFormEntity entitydata = new UrlEncodedFormEntity(paramPairs, HTTP.UTF_8); 
        HttpPost post = new HttpPost(requestUrl); 
        post.setEntity(entitydata); 
        DefaultHttpClient client = new DefaultHttpClient();  
        // 執行POST方式請求  
        HttpResponse response = client.execute(post); 
        if(response.getStatusLine().getStatusCode()==200){ 
            return response.getEntity().getContent(); 
        } 
         
        return null; 
    } 
 

package com.everyone.android.net;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import com.everyone.android.callback.ParseCallback;
import com.everyone.android.callback.ResultCallback;

/**
 * 功能描述:通過HTTPS協議發送POST網絡請求
 * @author android_ls
 *
 */
public class AsyncHttpsPost extends AsyncBaseRequest {

 /**
  *
  */
 private static final long serialVersionUID = 4L;

 public AsyncHttpsPost(String url, Map<String, String> parameter,
   ParseCallback handler, ResultCallback requestCallback) {
  super(url, parameter, handler, requestCallback);
 }

 @Override
 protected InputStream getRequestResult() throws IOException {
     List<NameValuePair> paramPairs = new ArrayList<NameValuePair>();
        if(parameter != null && !parameter.isEmpty()){
            for(Map.Entry<String, String> entry : parameter.entrySet()){
                paramPairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
       
        UrlEncodedFormEntity entitydata = new UrlEncodedFormEntity(paramPairs, HTTP.UTF_8);
        HttpPost post = new HttpPost(requestUrl);
        post.setEntity(entitydata);
        DefaultHttpClient client = new DefaultHttpClient();
        // 執行POST方式請求
        HttpResponse response = client.execute(post);
        if(response.getStatusLine().getStatusCode()==200){
            return response.getEntity().getContent();
        }
       
  return null;
 }

}
二、獲取用戶的基本信息

       向服務器端發送請求,獲取用戶的基本信息。注:為什麼要使用HTTPS協議發送請求?官方給出的理由,使用HTTPS協議調用API接口可以免去SIG認證。

         1、獲取用戶信息所需的參數

[java]
String url = "https://api.renren.com/restserver.do"; 
Map<String, String> parameter = new HashMap<String, String>(); 
parameter.put("v", "1.0"); // API的版本號,固定值為1.0   
parameter.put("access_token", accessToken); // OAuth2.0驗證授權後獲得的token。  
parameter.put("format", "JSON"); // 返回值的格式。請指定為JSON或者XML,推薦使用JSON,缺省值為XML   
parameter.put("call_id", "1.0"); // 請求隊列號   
parameter.put("method", "users.getInfo"); // 你要訪問那個接口,我們肯定調用獲取用戶的信息的接口咯,該接口支持批量獲取。 

        String url = "https://api.renren.com/restserver.do";
        Map<String, String> parameter = new HashMap<String, String>();
        parameter.put("v", "1.0"); // API的版本號,固定值為1.0
        parameter.put("access_token", accessToken); // OAuth2.0驗證授權後獲得的token。
        parameter.put("format", "JSON"); // 返回值的格式。請指定為JSON或者XML,推薦使用JSON,缺省值為XML
        parameter.put("call_id", "1.0"); // 請求隊列號
        parameter.put("method", "users.getInfo"); // 你要訪問那個接口,我們肯定調用獲取用戶的信息的接口咯,該接口支持批量獲取。       注:AccessToken的值我們之前有在本地存儲的,獲取的方式如下:

[java]
mAuthTokenManager = new AuthTokenManager(this); 
String accessToken = mAuthTokenManager.getAccessToken(); 
LogUtil.e("EveryoneActivity", "accessToken = " + accessToken); 

        mAuthTokenManager = new AuthTokenManager(this);
        String accessToken = mAuthTokenManager.getAccessToken();
        LogUtil.e("EveryoneActivity", "accessToken = " + accessToken);
       2、發送異步網絡請求

[java]
AsyncBaseRequest asyncHttpsPost = new AsyncHttpsPost(url, parameter, new ParseCallback() { 
     
    @Override 
    public Object parse(String json) throws JSONException { 
        LogUtil.i("EveryoneActivity", "json = " + json); 
         
        return null; 
    } 
}, new ResultCallback() { 
     
    @Override 
    public void onSuccess(Object obj) { 
       
    } 
     
    @Override 
    public void onFail(int errorCode) { 
        // TODO Auto-generated method stub  
    } 
}); 
 
mDefaultThreadPool.execute(asyncHttpsPost); 
mAsyncRequests.add(asyncHttpsPost); 

        AsyncBaseRequest asyncHttpsPost = new AsyncHttpsPost(url, parameter, new ParseCallback() {
           
            @Override
            public Object parse(String json) throws JSONException {
                LogUtil.i("EveryoneActivity", "json = " + json);
               
                return null;
            }
        }, new ResultCallback() {
           
            @Override
            public void onSuccess(Object obj) {
             
            }
           
            @Override
            public void onFail(int errorCode) {
                // TODO Auto-generated method stub
            }
        });
       
        mDefaultThreadPool.execute(asyncHttpsPost);
        mAsyncRequests.add(asyncHttpsPost);       3、網絡請求返回的JSON

[plain]

     { 
         "uid":461345584, 
         "tinyurl":"http://hdn.xnimg.cn/photos/hdn521/20130319/1930/h_tiny_zggz_8829000002e6113e.jpg", 
         "vip":1, 
         "sex":1, 
         "name":"逐鹿。。。", 
         "star":1, 
         "headurl":"http://hdn.xnimg.cn/photos/hdn521/20130319/1930/h_head_jbdD_8829000002e6113e.jpg", 
         "zidou":0 
     } 

        [
             {
                 "uid":461345584,
                 "tinyurl":"http://hdn.xnimg.cn/photos/hdn521/20130319/1930/h_tiny_zggz_8829000002e6113e.jpg",
                 "vip":1,
                 "sex":1,
                 "name":"逐鹿。。。",
                 "star":1,
                 "headurl":"http://hdn.xnimg.cn/photos/hdn521/20130319/1930/h_head_jbdD_8829000002e6113e.jpg",
                 "zidou":0
             }
        ]
       4、對JSON進行解析(這裡我們要自己一個字段一個字段的去解嗎?不用,我給大家推薦使用谷歌GSON去進行解析。不知道的可以到網上搜下GSON,下載一個jar包導入工程就可以了。)

[java]
new ParseCallback() { 
   
  @Override 
  public Object parse(String json) throws JSONException { 
      LogUtil.i("EveryoneActivity", "json = " + json); 
       
      Gson gson = new Gson(); 
      java.lang.reflect.Type type = new TypeToken<LinkedList<UserBasicInfo>>(){}.getType(); 
      LinkedList<UserBasicInfo> userList = gson.fromJson(json, type); 
      return userList.get(0); 
  } 

          new ParseCallback() {
           
            @Override
            public Object parse(String json) throws JSONException {
                LogUtil.i("EveryoneActivity", "json = " + json);
               
                Gson gson = new Gson();
                java.lang.reflect.Type type = new TypeToken<LinkedList<UserBasicInfo>>(){}.getType();
                LinkedList<UserBasicInfo> userList = gson.fromJson(json, type);
                return userList.get(0);
            }
          }       5、將解析後的結果返回

[java]
new ResultCallback() { 
     
    @Override 
    public void onSuccess(Object obj) { 
        UserBasicInfo userBasic = (UserBasicInfo)obj; 
        LogUtil.i("EveryoneActivity", "userBasic = " + userBasic.toString()); 
         
    } 
     
    @Override 
    public void onFail(int errorCode) { 
        // TODO Auto-generated method stub  
    } 

        new ResultCallback() {
           
            @Override
            public void onSuccess(Object obj) {
                UserBasicInfo userBasic = (UserBasicInfo)obj;
                LogUtil.i("EveryoneActivity", "userBasic = " + userBasic.toString());
               
            }
           
            @Override
            public void onFail(int errorCode) {
                // TODO Auto-generated method stub
            }
        }三、發送網絡請求,並解析返回結果的完整代碼如下:

[java]
mAuthTokenManager = new AuthTokenManager(this); 
String accessToken = mAuthTokenManager.getAccessToken(); 
LogUtil.e("EveryoneActivity", "accessToken = " + accessToken); 
 
// 獲取用戶信息所需的參數  
String url = "https://api.renren.com/restserver.do"; 
Map<String, String> parameter = new HashMap<String, String>(); 
parameter.put("v", "1.0"); // API的版本號,固定值為1.0   
parameter.put("access_token", accessToken); // OAuth2.0驗證授權後獲得的token。  
parameter.put("format", "JSON"); // 返回值的格式。請指定為JSON或者XML,推薦使用JSON,缺省值為XML   
parameter.put("call_id", "1.0"); // 請求隊列號   
parameter.put("method", "users.getInfo"); // 你要訪問那個接口,我們肯定調用用獲取用戶的信息的接口咯,該接口支持批量獲取。  
 
AsyncBaseRequest asyncHttpsPost = new AsyncHttpsPost(url, parameter, new ParseCallback() { 
 
    @Override 
    public Object parse(String json) throws JSONException { 
        LogUtil.i("EveryoneActivity", "json = " + json); 
 
        Gson gson = new Gson(); 
        java.lang.reflect.Type type = new TypeToken<LinkedList<UserBasicInfo>>() { 
        }.getType(); 
        LinkedList<UserBasicInfo> userList = gson.fromJson(json, type); 
        return userList.get(0); 
    } 
}, new ResultCallback() { 
 
    @Override 
    public void onSuccess(Object obj) { 
        UserBasicInfo userBasic = (UserBasicInfo) obj; 
        LogUtil.i("EveryoneActivity", "userBasic = " + userBasic.toString()); 
 
    } 
 
    @Override 
    public void onFail(int errorCode) { 
        // TODO Auto-generated method stub  
    } 
}); 
 
mDefaultThreadPool.execute(asyncHttpsPost); 
mAsyncRequests.add(asyncHttpsPost); 

        mAuthTokenManager = new AuthTokenManager(this);
        String accessToken = mAuthTokenManager.getAccessToken();
        LogUtil.e("EveryoneActivity", "accessToken = " + accessToken);

        // 獲取用戶信息所需的參數
        String url = "https://api.renren.com/restserver.do";
        Map<String, String> parameter = new HashMap<String, String>();
        parameter.put("v", "1.0"); // API的版本號,固定值為1.0
        parameter.put("access_token", accessToken); // OAuth2.0驗證授權後獲得的token。
        parameter.put("format", "JSON"); // 返回值的格式。請指定為JSON或者XML,推薦使用JSON,缺省值為XML
        parameter.put("call_id", "1.0"); // 請求隊列號
        parameter.put("method", "users.getInfo"); // 你要訪問那個接口,我們肯定調用用獲取用戶的信息的接口咯,該接口支持批量獲取。

        AsyncBaseRequest asyncHttpsPost = new AsyncHttpsPost(url, parameter, new ParseCallback() {

            @Override
            public Object parse(String json) throws JSONException {
                LogUtil.i("EveryoneActivity", "json = " + json);

                Gson gson = new Gson();
                java.lang.reflect.Type type = new TypeToken<LinkedList<UserBasicInfo>>() {
                }.getType();
                LinkedList<UserBasicInfo> userList = gson.fromJson(json, type);
                return userList.get(0);
            }
        }, new ResultCallback() {

            @Override
            public void onSuccess(Object obj) {
                UserBasicInfo userBasic = (UserBasicInfo) obj;
                LogUtil.i("EveryoneActivity", "userBasic = " + userBasic.toString());

            }

            @Override
            public void onFail(int errorCode) {
                // TODO Auto-generated method stub
            }
        });

        mDefaultThreadPool.execute(asyncHttpsPost);
        mAsyncRequests.add(asyncHttpsPost);     附帶:用戶基本信息實體類

[java]
package com.everyone.android.entity; 
 
/**
 * 功能描述:用戶基本信息實體類
 * @author android_ls
 *
 */ 
public class UserBasicInfo { 
 
    private int uid; // 用戶id   
 
    private String tinyurl; // 頭像鏈接 50*50大小   
 
    private int sex; // 性別,值1表示男性;值0表示女性   
 
    private String name; // 用戶名   
 
    private int star; // 是否為星級用戶,值“1”表示“是”;值“0”表示“不是”   
 
    private String headurl; // 頭像鏈接 100*100大小   
 
    private int zidou; // 是否為vip用戶,值1表示是;值0表示不是   
 
    private int vip; // 是否為vip用戶等級,前提是zidou節點必須為1   
 
    public int getUid() { 
        return uid; 
    } 
 
    public void setUid(int uid) { 
        this.uid = uid; 
    } 
 
    public String getTinyurl() { 
        return tinyurl; 
    } 
 
    public void setTinyurl(String tinyurl) { 
        this.tinyurl = tinyurl; 
    } 
 
    public int getSex() { 
        return sex; 
    } 
 
    public void setSex(int sex) { 
        this.sex = sex; 
    } 
 
    public String getName() { 
        return name; 
    } 
 
    public void setName(String name) { 
        this.name = name; 
    } 
 
    public int getStar() { 
        return star; 
    } 
 
    public void setStar(int star) { 
        this.star = star; 
    } 
 
    public String getHeadurl() { 
        return headurl; 
    } 
 
    public void setHeadurl(String headurl) { 
        this.headurl = headurl; 
    } 
 
    public int getZidou() { 
        return zidou; 
    } 
 
    public void setZidou(int zidou) { 
        this.zidou = zidou; 
    } 
 
    public int getVip() { 
        return vip; 
    } 
 
    public void setVip(int vip) { 
        this.vip = vip; 
    } 
 
    @Override 
    public String toString() { 
        return "UserBasicInfo [uid=" + uid + ", tinyurl=" + tinyurl + ", sex=" + sex + ", name=" + name + ", star=" + star + ", headurl=" 
                + headurl + ", zidou=" + zidou + ", vip=" + vip + "]"; 
    } 
 

package com.everyone.android.entity;

/**
 * 功能描述:用戶基本信息實體類
 * @author android_ls
 *
 */
public class UserBasicInfo {

    private int uid; // 用戶id

    private String tinyurl; // 頭像鏈接 50*50大小

    private int sex; // 性別,值1表示男性;值0表示女性

    private String name; // 用戶名

    private int star; // 是否為星級用戶,值“1”表示“是”;值“0”表示“不是”

    private String headurl; // 頭像鏈接 100*100大小

    private int zidou; // 是否為vip用戶,值1表示是;值0表示不是

    private int vip; // 是否為vip用戶等級,前提是zidou節點必須為1

    public int getUid() {
        return uid;
    }

    public void setUid(int uid) {
        this.uid = uid;
    }

    public String getTinyurl() {
        return tinyurl;
    }

    public void setTinyurl(String tinyurl) {
        this.tinyurl = tinyurl;
    }

    public int getSex() {
        return sex;
    }

    public void setSex(int sex) {
        this.sex = sex;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getStar() {
        return star;
    }

    public void setStar(int star) {
        this.star = star;
    }

    public String getHeadurl() {
        return headurl;
    }

    public void setHeadurl(String headurl) {
        this.headurl = headurl;
    }

    public int getZidou() {
        return zidou;
    }

    public void setZidou(int zidou) {
        this.zidou = zidou;
    }

    public int getVip() {
        return vip;
    }

    public void setVip(int vip) {
        this.vip = vip;
    }

    @Override
    public String toString() {
        return "UserBasicInfo [uid=" + uid + ", tinyurl=" + tinyurl + ", sex=" + sex + ", name=" + name + ", star=" + star + ", headurl="
                + headurl + ", zidou=" + zidou + ", vip=" + vip + "]";
    }

}       這篇就先聊到這裡,上面獲取的用戶信息裡,有用戶圖像的URL,也就是說關聯到了圖片在本地的存儲與處理。下一篇我們聊一聊圖片的雙緩存處理,敬請期待。。。

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved