申请了网易微博的API接口的Key,但是确实不太会用。于是在网上找了一个间接的方法,是C#写的,自己的博客是PHP的,所以就动手改成了PHP,并集成到自己的博客上。
不知道是不是我已经申请Key成功过,还是电脑里的Cookie没有清空掉,我在获取时并没有提供我的登录Cookie都OK!
下面是ASP.Net(C#)代码和PHP代码:
using System;
using System.Net;
using System.IO;
using System.Text;
public partial class weibo_Get163 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://t.163.com/statuses/user_timeline/iawen.json"); // iawen是我的用户名
request.Timeout = 15000; // 设置超时时间
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";//模拟IE7浏览器:
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(request.RequestUri, new Cookie("NTES_SESS", "我的登录Cookie"));
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(response.CharacterSet));
string content = reader.ReadToEnd();
reader.Close();
response.Close();
Response.Charset = response.CharacterSet;
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(2)); // 设置过期时间为两分钟
Response.Write(content);
}
}
//设置页面编码格式
header('Content-type:text/html; charset=UTF-8');
$html = fetch_page('163','http://t.163.com/statuses/user_timeline/iawen.json');
$arry=json_decode($html, true);
//开始输出微博列表
$weibo='';';
foreach ($arry as $i => $value) {
$weibo.=''.$arry[$i]['user']['name'].':'.$arry[$i]['text'].'';
';
$weibo.='Post:'. date("Y-m-d H:i",strtotime($arry[$i]['created_at'])).'';
$weibo.='[提交自'.$arry[$i]['source'].']
}
$weibo.='
echo $weibo;
function fetch_page($site,$url,$params=false)
{
$ch = curl_init();
//curl_setopt($ch, CURLOPT_COOKIE, 'NTES_SESS'.'我的登录Cookie');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 4);
if($params)
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
//设置浏览器代理和请求的URL
curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3');
curl_setopt($ch, CURLOPT_URL,$url);
$result = curl_exec($ch);
return $result;
}
?>
fetch_page函数也是我网上找的,根据自己的情况略有修改!
你好请问一下,用php模拟登陆网易微博应该怎么写呢