第一篇:基于Python的全國(guó)郵政編碼查詢api調(diào)用代碼實(shí)例
基于Python的全國(guó)郵政編碼查詢api調(diào)用代碼實(shí)例
代碼描述:基于Python的全國(guó)郵政編碼查詢api調(diào)用代碼實(shí)例 代碼平臺(tái):聚合數(shù)據(jù)
#!/usr/bin/python
#-*-coding: utf-8-*-importjson, urllib
fromurllib importurlencode
#---# 郵編查詢調(diào)用示例代碼 - 聚合數(shù)據(jù)
# 在線接口文檔:http://004km.cn/postcode/query“
params ={
”postcode“: ”“, #郵編,如:215001
”key“: appkey, #應(yīng)用APPKEY(應(yīng)用詳細(xì)頁(yè)查詢)
”page“: ”“, #頁(yè)數(shù),默認(rèn)1
”pagesize“: ”“, #每頁(yè)返回,默認(rèn):20,最大不超過(guò)50
”dtype“: ”“, #返回?cái)?shù)據(jù)的格式,xml或json,默認(rèn)json
}
params =urlencode(params)ifm ==”GET“:
f =urllib.urlopen(”%s?%s“%(url, params))
else:
f =urllib.urlopen(url, params)
”])
content =f.read()
res =json.loads(content)ifres:
error_code =res[“error_code”]
iferror_code ==0:
#成功請(qǐng)求
printres[“result”]
else:
print“%s:%s”%(res[“error_code”],res[“reason else:
print”request api error“
#省份城市區(qū)域列表
defrequest2(appkey, m=”GET“):
url =”http://v.juhe.cn/postcode/pcd“
params ={
”key“: appkey, #應(yīng)用APPKEY(應(yīng)用詳細(xì)頁(yè)查詢)
”dtype“: ”“, #返回?cái)?shù)據(jù)的格式,xml或json,默認(rèn)json
}
params =urlencode(params)ifm ==”GET“:
f =urllib.urlopen(”%s?%s“%(url, params))else:
f =urllib.urlopen(url, params)
content =f.read()
res =json.loads(content)ifres:
error_code =res[”error_code“]
iferror_code ==0:
#成功請(qǐng)求
printres[”result“]
else:
print”%s:%s“%(res[”error_code“],res[”reason
“])
else:
print”request api error“
#地名查詢郵編 defrequest3(appkey, m=”GET“):
url =”http://v.juhe.cn/postcode/search“
params ={
”pid“: ”“, #省份ID
”cid“: ”“, #城市ID
”did“: ”“, #區(qū)域ID
”q“: ”“, #地名關(guān)鍵字,如:木瀆
”key“: appkey, #應(yīng)用APPKEY(應(yīng)用詳細(xì)頁(yè)查詢)
”dtype“: ”“, #返回?cái)?shù)據(jù)的格式,xml或json,默認(rèn)json
}
params =urlencode(params)ifm ==”GET“:
f =urllib.urlopen(”%s?%s“%(url, params))else:
f =urllib.urlopen(url, params)
content =f.read()
res =json.loads(content)ifres:
error_code =res[”error_code“]
iferror_code ==0:
#成功請(qǐng)求
printres[”result“]
else:
print”%s:%s“%(res[”error_code“],res[”reason
“])
else:
print”request api error"
if__name__ =='__main__':
main()
第二篇:基于GO的搞笑段子api調(diào)用代碼實(shí)例
基于GO的搞笑段子api調(diào)用代碼實(shí)例
代碼描述:基于GO的搞笑段子api調(diào)用代碼實(shí)例 代碼平臺(tái):聚合數(shù)據(jù)
package main import(“io/ioutil”
“net/http”
“net/url”
“fmt”
“encoding/json”)
//---
// 笑話大全調(diào)用示例代碼 - 聚合數(shù)據(jù)
// 在線接口文檔:http://004km.cn/funny/type.from“
//初始化參數(shù)
param:=url.Values{}
//配置請(qǐng)求參數(shù),方法內(nèi)部已處理urlencode問(wèn)題,中文參數(shù)可以直接傳參
param.Set(”key“,APPKEY)//您申請(qǐng)的key
//發(fā)送請(qǐng)求
data,err:=Get(juheURL,param)
if err!=nil{
fmt.Errorf(”請(qǐng)求失敗,錯(cuò)誤信息:rn%v“,err)
}else{
var netReturn map[string]interface{}
json.Unmarshal(data,&netReturn)
if netReturn[”error_code“].(float64)==0{
fmt.Printf(”接口返回result字段是:rn%v“,netReturn[”result“])
}
} }
//2.根據(jù)接口序號(hào)查詢 func Request2(){
//請(qǐng)求地址
juheURL :=”http://japi.juhe.cn/funny/list.from“
//初始化參數(shù)
param:=url.Values{}
//配置請(qǐng)求參數(shù),方法內(nèi)部已處理urlencode問(wèn)題,中文參數(shù)可以直接傳參
param.Set(”cat“,”“)//指定接口類型,默認(rèn)
1param.Set(”st“,”“)//指定開始數(shù),默認(rèn)0
param.Set(”count“,”“)//指定返回個(gè)數(shù),默認(rèn)1
param.Set(”key“,APPKEY)//您申請(qǐng)的key
//發(fā)送請(qǐng)求
data,err:=Get(juheURL,param)
if err!=nil{
fmt.Errorf(”請(qǐng)求失敗,錯(cuò)誤信息:rn%v“,err)
}else{
var netReturn map[string]interface{}
json.Unmarshal(data,&netReturn)if netReturn[”error_code“].(float64)==0{
fmt.Printf(”接口返回result字段是:rn%v“,netReturn[”result“])
}
} }
//3.按類搜索接口 func Request3(){
//請(qǐng)求地址
juheURL :=”http://japi.juhe.cn/funny/search.from“
//初始化參數(shù)
param:=url.Values{}
//配置請(qǐng)求參數(shù),方法內(nèi)部已處理urlencode問(wèn)題,中文參數(shù)可以直接傳參
param.Set(”st“,”“)//指定開始數(shù),默認(rèn)0
param.Set(”count“,”“)//指定返回?cái)?shù)量,默認(rèn)1
param.Set(”term“,”“)//指定搜索關(guān)鍵詞
param.Set(”key“,APPKEY)//您申請(qǐng)的key
//發(fā)送請(qǐng)求
data,err:=Get(juheURL,param)
if err!=nil{
fmt.Errorf(”請(qǐng)求失敗,錯(cuò)誤信息:rn%v“,err)
}else{
var netReturn map[string]interface{}
json.Unmarshal(data,&netReturn)
if netReturn[”error_code“].(float64)==0{
fmt.Printf(”接口返回result字段是:rn%v“,netReturn[”result“])
}
} }
//4.參考答案接口 func Request4(){
//請(qǐng)求地址
juheURL :=”http://japi.juhe.cn/funny/answer.from“
//初始化參數(shù)
param:=url.Values{}
//配置請(qǐng)求參數(shù),方法內(nèi)部已處理urlencode問(wèn)題,中文參數(shù)可以直接傳參
param.Set(”id“,”“)//指定謎語(yǔ)、歇后語(yǔ)、打油詩(shī)、腦筋急轉(zhuǎn)彎編號(hào)
//發(fā)送請(qǐng)求
data,err:=Get(juheURL,param)
if err!=nil{
fmt.Errorf(”請(qǐng)求失敗,錯(cuò)誤信息:rn%v“,err)
}else{
var netReturn map[string]interface{}
json.Unmarshal(data,&netReturn)
if netReturn[”error_code“].(float64)==0{
fmt.Printf(”接口返回result字段是:rn%v“,netReturn[”result“])
}
} }
// get 網(wǎng)絡(luò)請(qǐng)求
func Get(apiURL string,params url.Values)(rs[]byte ,err error){
var Url *url.URL
Url,err=url.Parse(apiURL)
if err!=nil{
fmt.Printf(”解析url錯(cuò)誤:rn%v“,err)
return nil,err
}
//如果參數(shù)中有中文參數(shù),這個(gè)方法會(huì)進(jìn)行URLEncode
Url.RawQuery=params.Encode()
resp,err:=http.Get(Url.String())
if err!=nil{
fmt.Println(”err:",err)
return nil,err
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)}
// post 網(wǎng)絡(luò)請(qǐng)求 ,params 是url.Values類型
func Post(apiURL string, params url.Values)(rs[]byte,err error){
resp,err:=http.PostForm(apiURL, params)
if err!=nil{
return nil ,err }
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)}
第三篇:基于JAVA的輕笑話接口調(diào)用代碼實(shí)例
基于JAVA的輕笑話接口調(diào)用代碼實(shí)例
代碼描述:基于JAVA的輕笑話接口調(diào)用代碼實(shí)例 代碼平臺(tái):聚合數(shù)據(jù)
import java.io.BufferedReader;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.net.URL;
import java.net.URLEncoder;import java.util.HashMap;import java.util.Map;
import net.sf.json.JSONObject;
/**
*笑話大全調(diào)用示例代碼 - 聚合數(shù)據(jù)
*在線接口文檔:http://, like Gecko)Chrome/29.0.1547.66 Safari/537.36“;
//配置您申請(qǐng)的KEY
public static final String APPKEY =”*************************“;
//1.返回接口類型
public static void getRequest1(){
String result =null;
String url =”http://japi.juhe.cn/funny/type.from“;//請(qǐng)求接口地址
Map params = new HashMap();//請(qǐng)求參數(shù)
params.put(”key“,APPKEY);//您申請(qǐng)的key
try {
result =net(url, params, ”GET“);
JSONObject object = JSONObject.fromObject(result);
if(object.getInt(”error_code“)==0){
System.out.println(object.get(”result“));
}else{
System.out.println(object.get(”error_code“)+”:“+object.get(”reason“));
}
} catch(Exception e){
e.printStackTrace();
}
}
//2.根據(jù)接口序號(hào)查詢
public static void getRequest2(){
String result =null;
String url =”http://japi.juhe.cn/funny/list.from“;//請(qǐng)求接口地址
Map params = new HashMap();//請(qǐng)求參數(shù)
params.put(”cat“,”“);//指定接口類型,默認(rèn)
1params.put(”st“,”“);//指定開始數(shù),默認(rèn)0
params.put(”count“,”“);//指定返回個(gè)數(shù),默認(rèn)1
params.put(”key“,APPKEY);//您申請(qǐng)的key
try {
result =net(url, params, ”GET“);
JSONObject object = JSONObject.fromObject(result);
if(object.getInt(”error_code“)==0){
System.out.println(object.get(”result“));
}else{
System.out.println(object.get(”error_code“)+”:“+object.get(”reason“));
}
} catch(Exception e){
e.printStackTrace();
}
}
//3.按類搜索接口
public static void getRequest3(){
String result =null;
String url =”http://japi.juhe.cn/funny/search.from“;//請(qǐng)求接口地址 Map params = new HashMap();//請(qǐng)求參數(shù)
params.put(”st“,”“);//指定開始數(shù),默認(rèn)0
params.put(”count“,”“);//指定返回?cái)?shù)量,默認(rèn)1
params.put(”term“,”“);//指定搜索關(guān)鍵詞
params.put(”key“,APPKEY);//您申請(qǐng)的key
try {
result =net(url, params, ”GET“);
JSONObject object = JSONObject.fromObject(result);
if(object.getInt(”error_code“)==0){
System.out.println(object.get(”result“));
}else{
System.out.println(object.get(”error_code“)+”:“+object.get(”reason“));
}
} catch(Exception e){
e.printStackTrace();
}
}
//4.參考答案接口
public static void getRequest4(){
String result =null;
String url =”http://japi.juhe.cn/funny/answer.from“;//請(qǐng)求接口地址
Map params = new HashMap();//請(qǐng)求參數(shù)
params.put(”id“,”“);//指定謎語(yǔ)、歇后語(yǔ)、打油詩(shī)、腦筋急轉(zhuǎn)彎編號(hào)
try {
result =net(url, params, ”GET“);
JSONObject object = JSONObject.fromObject(result);
if(object.getInt(”error_code“)==0){
System.out.println(object.get(”result“));
}else{
System.out.println(object.get(”error_code“)+”:“+object.get(”reason“));
}
} catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args){
}
/**
*
* @param strUrl 請(qǐng)求地址
* @param params 請(qǐng)求參數(shù)
* @param method 請(qǐng)求方法
* @return 網(wǎng)絡(luò)請(qǐng)求字符串
* @throws Exception
*/
public static String net(String strUrl, Map params,String method)throws Exception {
HttpURLConnection conn = null;
BufferedReader reader = null;
String rs = null;
try {
StringBuffer sb = new StringBuffer();
if(method==null || method.equals(”GET“)){
strUrl = strUrl+”?“+urlencode(params);
}
URL url = new URL(strUrl);
conn =(HttpURLConnection)url.openConnection();
if(method==null || method.equals(”GET“)){
conn.setRequestMethod(”GET“);
}else{
conn.setRequestMethod(”POST“);
conn.setDoOutput(true);
}
conn.setRequestProperty(”User-agent“, userAgent);
conn.setUseCaches(false);
conn.setConnectTimeout(DEF_CONN_TIMEOUT);
conn.setReadTimeout(DEF_READ_TIMEOUT);
conn.setInstanceFollowRedirects(false);
conn.connect();
if(params!= null && method.equals(”POST“)){
try {
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(urlencode(params));
} catch(Exception e){
// TODO: handle exception
} }
InputStream is = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
String strRead = null;
while((strRead = reader.readLine())!= null){
sb.append(strRead);
}
rs = sb.toString();
} catch(IOException e){
e.printStackTrace();
} finally {
if(reader!= null){
reader.close();
}
if(conn!= null){
conn.disconnect();
}
}
return rs;
}
//將map型轉(zhuǎn)為請(qǐng)求參數(shù)型
public static String urlencode(Map
StringBuilder sb = new StringBuilder();
for(Map.Entry i : data.entrySet()){
try {
sb.append(i.getKey()).append(”=“).append(URLEncoder.encode(i.getValue()+”“,”UTF-8“)).append(”&");
} catch(UnsupportedEncodingException e){
e.printStackTrace();
}
}
return sb.toString();
} }