1、API調用的第一步:購買API接口
關于API的購買這里就不過多陳述,網上一搜一大把,我這次教程使用的API是天行數據的API
2、獲取ID和Key (類似賬號密碼)
這里就把我的KEY送給大家免費調用:
這個是查詢全國疫情信息的API—可使用次數:100000
key=d557d60eeebe9fa695424a6e3930a8fd
1
3.使用你需要的請求示例(API文檔里會有)
3.使用API文檔里的請求示例()
public class DataTest {
public static String request(String httpUrl, String httpArg) {
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
//httpUrl = httpUrl + "?" + httpArg;
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.tRequestMethod("GET");
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append(" ");
}
reader.clo();
result = sbf.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static void main(String[] args) {
/**
* @param urlAll
* :請求接口
* @param httpArg
* :參數
* @return 返回結果
*/
String httpUrl = "http://api.tianapi.com/txapi/ncovcity/index?key=d557d60eeebe9fa695424a6e3930a8fd";
String httpArg="";
System.out.println(request(httpUrl,httpArg));
}
}
測試效果:
4.請求參數
5、添加請求參數,查詢2020年3月12日的全國疫情數據
修改后的代碼
public static String request(String httpUrl, String httpArg) {
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
httpUrl = httpUrl + "&" + httpArg;
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.tRequestMethod("GET");
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append(" ");
}
reader.clo();
result = sbf.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static void main(String[] args) {
/**
* @param urlAll
* :請求接口
* @param httpArg
* :參數
* @return 返回結果
*/
String httpUrl = "http://api.tianapi.com/txapi/ncovcity/index?key=d557d60eeebe9fa695424a6e3930a8fd";
String httpArg="date=2020-03-12";
System.out.println(request(httpUrl,httpArg));
}
}
測試結果
本文發布于:2023-02-28 20:58:00,感謝您對本站的認可!
本文鏈接:http://www.newhan.cn/zhishi/a/167771294999267.html
版權聲明:本站內容均來自互聯網,僅供演示用,請勿用于商業和其他非法用途。如果侵犯了您的權益請與我們聯系,我們將在24小時內刪除。
本文word下載地址:調用api接口(怎么調用api接口).doc
本文 PDF 下載地址:調用api接口(怎么調用api接口).pdf
| 留言與評論(共有 0 條評論) |
|