PHP调用示例
<?php
// 配置参数
$key = "你的接口密钥";
$category = "all"; // 新闻分类
$limit = 30; // 返回数量
$sort = "hot"; // 排序方式
// 拼接请求URL
$url = "http://api.41game.com/news/hotlist?key={$key}&category={$category}&limit={$limit}&sort={$sort}";
// 发起请求
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
// 解析结果
$result = json_decode($response, true);
if($result['code'] == 200){
echo "新闻查询成功,共返回".count($result['newslist'])."条数据
";
foreach($result['newslist'] as $news){
echo "标题:".$news['title']."
";
echo "热度:".$news['hotnum']."
";
echo "摘要:".$news['digest']."
";
}
}else{
echo "新闻查询失败:".$result['msg'];
}
?>
Python调用示例
import requests
# 配置参数
key = "你的接口密钥"
category = "all" # 新闻分类
limit = 30 # 返回数量
sort = "hot" # 排序方式
# 拼接请求URL
url = f"http://api.41game.com/news/hotlist?key={key}&category={category}&limit={limit}&sort={sort}"
# 发起请求
response = requests.get(url)
result = response.json()
# 解析结果
if result['code'] == 200:
print(f"新闻查询成功,共返回{len(result['newslist'])}条数据")
for news in result['newslist']:
print(f"标题:{news['title']}")
print(f"热度:{news['hotnum']}")
print(f"摘要:{news['digest']}")
print("-" * 50)
else:
print(f"新闻查询失败:{result['msg']}")
Java调用示例
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class NewsApiDemo {
public static void main(String[] args) {
try {
// 配置参数
String key = "你的接口密钥";
String category = "all"; // 新闻分类
int limit = 30; // 返回数量
String sort = "hot"; // 排序方式
// 拼接请求URL
String urlStr = String.format(
"http://api.41game.com/news/hotlist?key=%s&category=%s&limit=%d&sort=%s",
key, category, limit, sort
);
// 发起请求
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
// 读取响应
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = in.readLine()) != null) {
response.append(line);
}
in.close();
// 输出结果
System.out.println("接口返回结果:" + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
返回示例
{
"code":200,
"msg":"success",
"tip":"升级新域名提示:https://www.tianapi.com/article/195",
"newslist":[
{
"title":"全国人大会议闭幕会",
"hotnum":5974487,
"digest":"全国人大会议闭幕会"
},
{
"title":"全国人大表决通过\"十五五\"规划纲要",
"hotnum":5355238,
"digest":"全国人大表决通过\"十五五\"规划纲要"
},
{
"title":"代表建议将抗战胜利纪念日纳入法定假日",
"hotnum":5297349,
"digest":"代表建议将抗战胜利纪念日纳入法定假日"
}
]
}
{
"code":400,
"msg":"参数错误",
"tip":""
}