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

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



加入:、

 <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. mvc core 中使用 redis

    redis 下载安装路径: https://github.com/MicrosoftArchive/redis/releases 右键打开cmd命令行,运行命令:   .\redis-server.e ...

  2. egg.js上传文件到本地

    'use strict'; const Service = require('egg').Service; const fs = require('fs'); const path = require ...

  3. DB2隔离级别

    四.隔离级别与锁 数据库是利用锁和隔离级别来共同处理数据库的并发的.DB2数据库用来尝试实施并发性的方法之一是通过使用隔离级别,它决定在第一个事务访问数据时,如何对其他事务锁定或隔离该事务所使用的数据 ...

  4. build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing

    maven test项目时遇到一下错误 Some problems were encountered while building the effective model for cn.temptat ...

  5. vscode调试nodejs

    1.安装nodejs 2.安装vscode 3.vscode安装debugger for chrome插件 4.新建nodejs-test文件夹,新建server.js空白文件,添加内容: var h ...

  6. java 几种拼接字符串的效率问题

    拼接字符串,大致有3个class可以用,他们是String, StringBuffer,StringBuilder, StringBuilder是1.5中来代替StringBuffer的.检验方法如下 ...

  7. BNUOJ 26223 CosmoCraft

    CosmoCraft Time Limit: 1000ms Memory Limit: 32768KB This problem will be judged on HDU. Original ID: ...

  8. UVALive 6430 (水dp)

    https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_probl ...

  9. bzoj 2653 middle (可持久化线段树)

    middle Time Limit: 20 Sec  Memory Limit: 512 MBSubmit: 1981  Solved: 1097[Submit][Status][Discuss] D ...

  10. Codeforces908G. New Year and Original Order

    给n<=10^700,问1到n中每个数在各数位排序后得到的数的和.答案膜1e9+7. 一看就是数位DP啦..然而并没有什么思路.. 可以尝试统计n(i,j)表示数j在第i位的出现次数,知道了这个 ...