編輯:關於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,也就是說關聯到了圖片在本地的存儲與處理。下一篇我們聊一聊圖片的雙緩存處理,敬請期待。。。
最近項目裡要做一個簡單的曲線圖來標識數據,開始以為很簡單,android已經有那麼多的開源圖表庫了,什麼achartenginee,hellochart,mpandroi
下拉菜單美團首頁類似的下拉彈出菜單工程中經常遇到的控件,不同工程中菜單條目的類型與數量也不一樣所以需要根據實際需要填充不同內容。先寫個demo,一倍不時之需吧。既然每個項
PS:便宜的服務器可是會不定時的坑你一把。今天在修改app的一些交互以及重構代碼。一切都是那麼順利,啪啪啪,runing,測試沒問題,再啪啪啪。。。突然,測試上傳頭像的時
第1節 Activity的使用Activity幾乎是每個應用必有的組件,所以任何安卓應用的開發幾乎都是從Activity開始的。比如,你希望設計一個計算器應用,要呈現這個