笑话从哪里来?自己写肯定是不现实的。在这个“云”的时代,各种云都有,自然是不缺开放API的(大部分都是免费的)。随意一搜,果然被我找到一个接口:易源_笑话大全http://apistore.baidu.com/apiworks/servicedetail/864.html。下面写一个用Python写的例子,其实不止python语言,同样提供了C#,java等语言接口。
# -*- coding: utf-8 -*-
import sys, urllib, urllib2, json
url = 'http://apis.baidu.com/showapi_open_bus/showapi_joke/joke_text?page=1'
apikey="自己申请的key"
req = urllib2.Request(url)
req.add_header("apikey", apikey)
resp = urllib2.urlopen(req)
content = resp.read()
if(content):
#print(content)打印所有
json_result = json.loads(content) #转换为字典对象
content_list = json_result['showapi_res_body']['contentlist']
first_title = content_list[0]['title'].encode('utf8')
first_text = content_list[0]['text'].encode('utf8')
print '标题:'+first_title
print '内容:'+first_text
else:
print "error"
结果如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
namespace ConsoleApplication1
{
class Program
{
public static string request(string url, string param,string apikey)
{
string strURL = url + '?' + param;
System.Net.HttpWebRequest request;
request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
request.Method = "GET";
request.Headers.Add("apikey", apikey);
System.Net.HttpWebResponse response;
response = (System.Net.HttpWebResponse)request.GetResponse();
System.IO.Stream s;
s = response.GetResponseStream();
string StrDate = "";
string strValue = "";
StreamReader Reader = new StreamReader(s, Encoding.UTF8);
while ((StrDate = Reader.ReadLine()) != null)
{
strValue += StrDate + "\r\n";
}
return strValue;
}
static void Main(string[] args)
{
string url="http://apis.baidu.com/showapi_open_bus/showapi_joke/joke_text";
string param = "page=1";
string apikey = "自己申请的apikey";
Console.Write(request(url,param,apikey));
}
}
}