1,http请求,将paramList发送到http://api.renren.com/restserver.do进行post请求。
同时得到HttpResponse响应,判断响应代码是否为200,为200表示成功。解析JSON数据为相关对象。
private String sendRequest() {
String returnValue = "0";
httpClient = new DefaultHttpClient();
try {
HttpPost httpPost = new HttpPost(
"http://api.renren.com/restserver.do");
httpPost.setEntity(new UrlEncodedFormEntity(paramList, HTTP.UTF_8));// 添加请求参数到请求对象
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) { // 为200表示执行成功
strResult = EntityUtils.toString(httpResponse.getEntity()); // 得到返回数据(为JSON数据)
Log.i("RenrenFriendsActivity", "strResult:" + strResult);
if (!strResult.contains("error_code")) {
renrenList = RenrenUtil.parseRenrenFromJson(strResult); // 解析JSON数据为相应对象
returnValue = "1"; // 定义返回标志
}
}
} catch (ClientProtocolException e) {
strResult = e.getMessage().toString();
e.printStackTrace();
} catch (IOException e) {
strResult = e.getMessage().toString();
e.printStackTrace();
} catch (Exception e) {
strResult = e.getMessage().toString();
e.printStackTrace();
}
return returnValue;
}
2,解析Json:
/**
* 解析JSON数据为人人对象
*
* @param renrenJsonData
* @return
*/
public static List<Renren> parseRenrenFromJson(String renrenJsonData) {
List<Renren> renrenList = new ArrayList<Renren>();
try {
JSONArray jsonArray = new JSONArray(renrenJsonData);
int length = jsonArray.length();
for (int i = 0; i < length; ++i) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Renren renren = new Renren();
renren.setId(jsonObject.getString("id"));
renren.setName(jsonObject.getString("name"));
renren.setHeadurl(jsonObject.getString("headurl"));
renrenList.add(renren);
}
return renrenList;
} catch (JSONException e) {
}
return null;
}
写一个RenRen bean用来保存信息;
public class Renren {
protected String id;
protected String name;
protected String headurl;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHeadurl() {
return headurl;
}
public void setHeadurl(String headurl) {
this.headurl = headurl;
}
}
3,使用AsyncTask来异步网络连接和查询:
FriendsTask task = new FriendsTask();
task.execute("10");
FriendsTask的代码如下:
class FriendsTask extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... params) {
Log.i("FriendsTask", "----doInBackground----");
getParams();
return sendRequest();
}
@Override
protected void onCancelled() {
Log.i("FriendsTask", "----onCancelled----");
super.onCancelled();
}
@Override
protected void onPostExecute(String result) {
Log.i("FriendsTask", "----onPostExecute----");
Log.i("FriendsTask", "result:" + result);
// message.setText(result);
pDialog.dismiss();
if (result.equals("1")) {
mHandler.sendEmptyMessage(SUCCESS);
} else {
mHandler.sendEmptyMessage(FAILURE);
}
}
@Override
protected void onPreExecute() {
Log.i("FriendsTask", "----onPreExecute----");
// 任务启动,可以在这里显示一个对话框,这里简单处理
pDialog = ProgressDialog.show(RenrenFriendsActivity.this,
"Importing", "importing...");
}
@Override
protected void onProgressUpdate(Integer... values) {
// 更新进度
// message.setText(values[0]);
Log.i("FriendsTask", "---onProgressUpdate----");
}
}
4,使用一个adapter来适配listview,由于返回头像的时候只返回的是url,所以,通过新开一个线程来异步加载头像图片。
Adapter类如下:
class FriendsAdapater extends BaseAdapter {
private AsyncImageLoader asyncImageLoader = new AsyncImageLoader(); // 异步获取图片
TextView userName;
ImageView userImage;
public int getCount() {
return renrenList == null ? 0 : renrenList.size();
}
public Object getItem(int position) {
return renrenList == null ? null : renrenList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
convertView = LayoutInflater.from(getApplicationContext()).inflate(
R.layout.renren_friend_item, null);
userName = (TextView) convertView.findViewById(R.id.username);
userImage = (ImageView) convertView.findViewById(R.id.userimage);
Renren renren = renrenList.get(position);
if (renren != null) {
convertView.setTag(renren.getId());
userImage.setTag(renren.getHeadurl());
userName.setText(renren.getName());
// 异步加载图片并显示
Drawable cachedImage = asyncImageLoader.loadDrawable(renren,
new ImageCallback() {
public void imageLoaded(Drawable imageDrawable,
String imageUrl) {
ImageView imageView = (ImageView) friendsListView
.findViewWithTag(imageUrl);
if (imageView != null) {
imageView.setImageDrawable(imageDrawable);
}
}
});
if (cachedImage != null) {
userImage.setImageDrawable(cachedImage);
} else {// 如果没有图片,就以一个载入的图片代替显示
userImage.setImageResource(R.drawable.avatar_default);
}
}
return convertView;
}
}
异步加载图片的类AsyncImageLoader如下:
public class AsyncImageLoader {
private HashMap<String, SoftReference<Drawable>> imageCache; // 缓存图片
public AsyncImageLoader() {
imageCache = new HashMap<String, SoftReference<Drawable>>();
}
public Drawable loadDrawable(final Renren renren,
final ImageCallback imageCallback) {
final String imageId = renren.getId();
final String imageURL = renren.getHeadurl();
// 判断缓存中是否已经存在图片,如果存在则直接返回
if (imageCache.containsKey(imageId)) {
SoftReference<Drawable> softReference = imageCache.get(imageId);
Drawable drawable = softReference.get();
if (drawable != null) {
return drawable;
}
}
final Handler handler = new Handler() {
public void handleMessage(Message message) {
imageCallback.imageLoaded((Drawable) message.obj, imageURL);
}
};
// 开辟一个新线程去下载图片,并用Handler去更新UI
new Thread() {
@Override
public void run() {
Drawable drawable = loadImageFromUrl(imageURL);
imageCache.put(imageURL, new SoftReference<Drawable>(drawable));
Message message = handler.obtainMessage(0, drawable);
handler.sendMessage(message);
}
}.start();
return null;
}
// 从URL下载图片
public static Drawable loadImageFromUrl(String url) {
URL m;
InputStream i = null;
try {
m = new URL(url);
i = (InputStream) m.getContent();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Drawable d = Drawable.createFromStream(i, "src");
return d;
}
// 回调接口
public interface ImageCallback {
// 回调函数
public void imageLoaded(Drawable imageDrawable, String imageUrl);
}
}
好了,这样你就可以从人人网获取好友信息了。
更多接口请查看:
http://wiki.dev.renren.com/wiki/API#.E5.9F.BA.E7.A1.80API