前面把基本的东西讲完了,之后就是数据的获取和解析显示出来了,那接下来我们就负责抓取数据的这块吧,首先我们须要

在清单文件中载入服务和活动



加入:、

 <activity android:name="com.neweriweibo.activity.OAuthActivity"/>
<activity android:name=".MainActivity"/>
<activity android:name="com.neweriweibo.activity.SendMessageActivity"/> <!-- 获取自己微博信息 -->
<service android:name="com.neweriweibo.service.UserService"/> <!-- 获取全部微博的信息 -->
<service android:name="com.neweriweibo.service.WeiBoService"/>

以下看看用户个人信息的抓取:

package com.neweriweibo.service;
/**
* 个人信息数据抓取、
* @author Engineer-Jsp
* @date 2014.10.28
* */
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL; import org.json.JSONArray;
import org.json.JSONObject; import com.neweriweibo.model.User;
import com.neweriweibo.utils.TencentAPI; import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
public class UserService extends IntentService { public final static String UPDATA = "com.neweriweibo.service.UPDATA";
public final static String NOW_WEATHER = "UserWeiBo" ;
private StringBuffer _buff;
private File weibousercurrentFile;
private BufferedWriter write;
private BufferedWriter writefour;
private static BufferedReader reader ;
private String access_token;
private String openid;
private String openkey; public UserService(){
super("WeatherService") ;
}
@Override
public void onCreate() { super.onCreate();
weibousercurrentFile = new File(Environment.getExternalStorageDirectory(), "weiinfo");
if (!weibousercurrentFile.exists()) {
try {
weibousercurrentFile.createNewFile();// 创建
} catch (IOException e) {
e.printStackTrace();
}
}
access_token = PreferenceManager.getDefaultSharedPreferences(this).getString("access_token", "access_token");
openid = PreferenceManager.getDefaultSharedPreferences(this).getString("openid", "openid");
openkey = PreferenceManager.getDefaultSharedPreferences(this).getString("openkey", "openkey"); } @Override
public void onDestroy() { super.onDestroy(); } /**
* https://open.t.qq.com/api/user/info
* ? oauth_consumer_key=801506473
* &access_token=789a7d5284d0c3e608f8e384c993d04b
* &openid=0027BC08DB5B45D7461E9A0F16F527E7
* &clientip=CLIENTIP&oauth_version=2.a&scope=all
*/ @Override
protected void onHandleIntent(Intent intent) {
// oauth_consumer_key=801506545&access_token=c63ed52ee874eff6e61dfe66d2c7b396&openid=0027BC08DB5B45D7461E9A0F16F527E7&clientip=CLIENTIP&oauth_version=2.a&scope=all
// oauth_consumer_key=xx&access_token=xx&openid=xx&clientip=xx&oauth_version=2.a&scope=xx
User weibouser = new User();
StringBuffer buff = new StringBuffer(TencentAPI.userInfo) ;
buff.append("?").append("oauth_consumer_key="+TencentAPI.client_id )
.append("&access_token="+access_token)
.append("&openid="+openid)
.append("&clientip=CLIENTIP&oauth_version=2.a&scope=all") ; Log.i("获取当前登录账户个人信息的请求地址:", buff.toString()+"") ; try {
URL _url = new URL(buff.toString());
HttpURLConnection conn = (HttpURLConnection) _url.openConnection();
conn.setConnectTimeout(8000);
conn.setReadTimeout(8000);
conn.setDoOutput(false);
conn.setRequestMethod("GET"); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream in = conn.getInputStream();
InputStreamReader reader = new InputStreamReader(in, "utf-8");
BufferedReader buffere = new BufferedReader(reader);
StringBuilder builder = new StringBuilder();
String line = null;
while (null != (line = buffere.readLine())) {
builder.append(line);
} String json = builder.toString(); Log.i("获取当前登录账户个人信息的数据:", json.toString()+"\n") ;
// 解析数据 JSONObject root = new JSONObject(json).getJSONObject("data") ;
JSONArray tweetinfo = root.getJSONArray("tweetinfo");
Log.d("用户近期的一条原创微博:", tweetinfo.toString());
JSONObject zero = tweetinfo.getJSONObject(0);
String nearinfo = zero.getString("text");
Log.d("原创微博信息:", nearinfo.toString());
String nick = root.getString("nick") ;
String idolnum = root.getString("idolnum") ;
String location = root.getString("location") ;
String brithyear = root.getString("birth_year") ;
String brithmonth = root.getString("birth_month") ;
String brithday = root.getString("birth_day") ;
String introduction = root.getString("introduction") ;
String headimg = root.getString("head")+"/40";
String fansnum = root.getString("fansnum");
String tweetnum = root.getString("tweetnum");
String sex = root.getString("sex");
Log.d("sex内容測试,刚取得:", sex);
if(sex.equals("1")){
sex = "男";
}else if(sex.equals("2")){
sex = "女";
}else{
sex = "";
}
Log.d("sex内容測试,推断后:", sex);
write = new BufferedWriter(new FileWriter(weibousercurrentFile));
write.write(nick + "*" + idolnum + "*" + location+ "*" + brithyear+"/"+brithmonth+"/"+brithday+"*"+introduction+"*"+headimg+"*"+fansnum+"*"+tweetnum+"*"+sex+"*"+nearinfo);
write.close(); weibouser.setNick(nick) ;
weibouser.setIdonum(idolnum);
weibouser.setLoacation(location) ;
weibouser.setBirthyeaer(brithyear);
weibouser.setBirthmonth(brithmonth);
weibouser.setBirthday(brithday) ;
weibouser.setHeadimg(headimg);
weibouser.setInfo(introduction) ;
weibouser.setFansnum(fansnum);
weibouser.setTweetnum(tweetnum);
weibouser.setSex(sex);
weibouser.setNearinfo(nearinfo);
conn.disconnect();
} } catch (Exception e) {
e.printStackTrace();
} Intent _intent = new Intent(UPDATA);
Bundle mBundle = new Bundle();
mBundle.putParcelable(UserService.NOW_WEATHER, weibouser);
_intent.putExtras(mBundle); sendBroadcast(_intent) ; } }

常规的网络请求抓取数据。将解析到的数据存在User对象里,而且在本地用BuffereWriter保存了一份。方便下登录,且考虑在没有网络的情况下或者数据抓取失败的情况下不至于界面因没有数据而显得空洞,不美观

将获取的数据意图发送至应用程序,其它活动接收,并获取数据,显示在界面

User:

package com.neweriweibo.model;
/**
* 用户信息对象
* @author Engineer-Jsp
* @date 2014.10.28
* */
import android.os.Parcel;
import android.os.Parcelable; public class User implements Parcelable{ private String nick ;// 昵称
private String info ;// 自我介绍
private String loacation ;// 所在地
private String idonum ; //关注的人数 private String birthyeaer ;// 生日年
private String birthmonth ;// 生日月
private String birthday ;// 生日天
private String headimg;// 头像 private String fansnum;// 被关注数
private String tweetnum; // 发表的微博数
private String sex; // 性别
private String nearinfo; //用户近期的一条原创微博
public String getNearinfo() {
return nearinfo;
}
public void setNearinfo(String nearinfo) {
this.nearinfo = nearinfo;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getFansnum() {
return fansnum;
}
public void setFansnum(String fansnum) {
this.fansnum = fansnum;
}
public String getTweetnum() {
return tweetnum;
}
public void setTweetnum(String tweetnum) {
this.tweetnum = tweetnum;
} public String getHeadimg() {
return headimg;
}
public void setHeadimg(String headimg) {
this.headimg = headimg;
}
public String getNick() {
return nick;
}
public void setNick(String nick) {
this.nick = nick;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public String getLoacation() {
return loacation;
}
public void setLoacation(String loacation) {
this.loacation = loacation;
}
public String getIdonum() {
return idonum;
}
public void setIdonum(String idonum) {
this.idonum = idonum;
}
public String getBirthyeaer() {
return birthyeaer;
}
public void setBirthyeaer(String birthyeaer) {
this.birthyeaer = birthyeaer;
}
public String getBirthmonth() {
return birthmonth;
}
public void setBirthmonth(String birthmonth) {
this.birthmonth = birthmonth;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public User(String nick, String info, String loacation, String idonum,
String birthyeaer, String birthmonth, String birthday,String headimg,
String fansnum , String tweetnum,String sex,String nearinfo) {
super();
this.nick = nick;
this.info = info;
this.loacation = loacation;
this.idonum = idonum;
this.birthyeaer = birthyeaer;
this.birthmonth = birthmonth;
this.birthday = birthday;
this.headimg = headimg;
this.fansnum = fansnum;
this.tweetnum = tweetnum;
this.sex = sex;
this.nearinfo = nearinfo;
}
public User() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "User [昵称=" + nick + ", 自我介绍=" + info + ", 城市="
+ loacation + ", 关注数=" + idonum + ", 年="
+ birthyeaer + ", 月=" + birthmonth + ", 日="
+ birthday + ",头像地址="+headimg+",听众="+fansnum+",发表微博数="+tweetnum+",性别="+sex+
",近期动态="+nearinfo+"]";
} public static final Parcelable.Creator<User> CREATOR = new Creator<User>() { @Override
public User createFromParcel(Parcel source) {
// TODO Auto-generated method stub
User user = new User() ; user.nick = source.readString() ;
user.info = source.readString() ;
user.loacation = source.readString() ;
user.idonum = source.readString() ;
user.birthyeaer = source.readString() ;
user.birthmonth = source.readString() ;
user.birthday = source.readString() ;
user.headimg = source.readString();
user.fansnum = source.readString();
user.tweetnum = source.readString();
user.sex = source.readString();
user.nearinfo = source.readString();
return user;
} @Override
public User[] newArray(int size) {
// TODO Auto-generated method stub
return new User[size];
}
}; @Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
dest.writeString(nick);
dest.writeString(info);
dest.writeString(loacation);
dest.writeString(idonum);
dest.writeString(birthyeaer);
dest.writeString(birthmonth);
dest.writeString(birthday);
dest.writeString(headimg);
dest.writeString(fansnum);
dest.writeString(tweetnum);
dest.writeString(sex);
dest.writeString(nearinfo);
} }

UserService extends IntentService 重写onHandleIntent(Intent intent) 。事实上就相当于开启了一个子线程,来对网络请求进行处理,IntentService使用队列的方式将请求的Intent增加队列,然后开启一个worker thread(线程)来处理队列中的Intent,对于异步的startService请求,IntentService会处理完毕一个之后再处理第二个,每个请求都会在一个单独的worker
thread中处理,不会堵塞应用程序的主线程。这里就给我们提供了一个思路。假设有耗时的操作与其在Service里面开启新线程还不如使用IntentService来处理耗时操作

Android MaoZhuaWeiBo开发Service抓取个人信息-2的更多相关文章

  1. .net抓取网页信息 - Jumony框架使用1

    往往在实际开发中,经常会用到一些如抓取网站信息之类的的操作,往往大家采用的是用一些正则的方式获取,但是有时候正则是很死板的,我们常常试想能不能使用jquery的选择器,获取符合自己要求的元素,然后进行 ...

  2. SpringCloud系列九:SpringCloudConfig 基础配置(SpringCloudConfig 的基本概念、配置 SpringCloudConfig 服务端、抓取配置文件信息、客户端使用 SpringCloudConfig 进行配置、单仓库目录匹配、应用仓库自动选择、仓库匹配模式)

    1.概念:SpringCloudConfig 基础配置 2.具体内容 通过名词就可以发现,SpringCloudConfig 核心作用一定就在于进行配置文件的管理上.也就是说为了更好的进行所有微服务的 ...

  3. 网络爬虫: 从allitebooks.com抓取书籍信息并从amazon.com抓取价格(3): 抓取amazon.com价格

    通过上一篇随笔的处理,我们已经拿到了书的书名和ISBN码.(网络爬虫: 从allitebooks.com抓取书籍信息并从amazon.com抓取价格(2): 抓取allitebooks.com书籍信息 ...

  4. 网络爬虫: 从allitebooks.com抓取书籍信息并从amazon.com抓取价格(2): 抓取allitebooks.com书籍信息及ISBN码

    这一篇首先从allitebooks.com里抓取书籍列表的书籍信息和每本书对应的ISBN码. 一.分析需求和网站结构 allitebooks.com这个网站的结构很简单,分页+书籍列表+书籍详情页. ...

  5. PHP快速抓取快递信息

    <?php header("Content-type:text/html;charset=utf-8"); /** * Express.class.php 快递查询类 * @ ...

  6. HttpClient+Jsoup 抓取网页信息(网易贵金属为例)

    废话不多说直接讲讲今天要做的事. 利用HttpClient和Jsoup技术抓取网页信息.HttpClient是支持HTTP协议的客户端编程工具包,并且它支持HTTP协议. jsoup 是一款基于 Ja ...

  7. Web Scraper 高级用法——抓取属性信息 | 简易数据分析 16

    这是简易数据分析系列的第 16 篇文章. 这期课程我们讲一个用的较少的 Web Scraper 功能--抓取属性信息. 网页在展示信息的时候,除了我们看到的内容,其实还有很多隐藏的信息.我们拿豆瓣电影 ...

  8. [工具开发] Perl 爬虫脚本--从美国国家漏洞数据库抓取实时信息

    一.简介 美国国家漏洞数据库收集了操作系统,应用软件的大量漏洞信息,当有新的漏洞出现时,它也会及时发布出来. 由于信息量巨大,用户每次都需要到它的网站进行搜索,比较麻烦.如果能有个工具,每天自动分析它 ...

  9. PHP中CURL技术模拟登陆抓取网站信息,用与微信公众平台成绩查询

    伴随微信的红火,微信公众平台成为许多开发者的下一个目标.笔者本身对于这种新鲜事物没有如此多的吸引力.但是最近有朋友帮忙开发微信公众平台中一个成绩查询的功能.于是便在空余时间研究了一番. 主要的实现步骤 ...

随机推荐

  1. 07CSS表格

    CSS表格 表格边框 如需在 CSS 中设置表格边框,请使用 border 属性. table, th, td { border: 1px solid blue; } 折叠边框 border-coll ...

  2. 【原】简单shell练习(二)

    1.查找awk # cat /etc/passwd |awk -F ':' 'BEGIN {print "name,shell"} {print $1","$7 ...

  3. filezilla server FTP 安装报错 "could not load TLS network. Aborting start of administration interface"

    filezilla server FTP 安装报错   "could not load TLS network. Aborting start of administration inter ...

  4. python清除字符串中无用字符

    将列表val_list中包含的非法字符去掉,illegal_char是非法字符列表 def clear(): illegal_char = [' ','#','%','_','@'] tmp_list ...

  5. oracle分析函数系列之sum(col1) over(partition by col2 order by col3):实现分组汇总或递增汇总

    语法:sum(col1) over(partition by col2 order by col3 )  准备数据: DEPT_ID    ENAME          SAL1 1000       ...

  6. RNNCell使用

    目录 Recap input dim, hidden dim SimpleRNNCell Single layer RNN Cell Multi-Layers RNN RNN Layer Recap ...

  7. leetcode-88合并两个有序数组

    合并两个有序数组 思路:利用索引合并两个列表,排序.注意不需要返回值,只修改nums1 class Solution: def merge(self, nums1: List[int], m: int ...

  8. 面试高峰期,如何应对面试官的jvm刁难,特写一篇jvm面经(第一部)

    已经进入三月份,正所谓金三银四,正是一年最好的招聘期,想必我的公号粉丝们一定有不少想要跳槽的吧,哈哈,/**偷偷告诉你们其实小编也准备跳槽*/(我要加个注释,被老板知道可就完蛋了),说到面试,想必大家 ...

  9. 在 Sublime Text 直接运行 Javascript 调试控制台

    转载自:http://www.jianshu.com/p/43b0726792f7 sublime text javascript Sublime Text是深受喜欢的多语言编辑器,很多开发人员都选择 ...

  10. api安全认证

    三.auth自定义授权 客户端代码: import requests import hashlib import time current_time = time.time() #自意义的字符串app ...