API接⼝调⽤⽅法(附上我的可⽤api)1、API调⽤的第⼀步:购买API接⼝
关于API的购买这⾥就不过多陈述,⽹上⼀搜⼀⼤把,我这次教程使⽤的API是天⾏数据的API
2、获取ID和Key (类似账号密码)
百度api接口这⾥就把我的KEY送给⼤家免费调⽤:
这个是查询全国疫情信息的API—可使⽤次数:100000
key=d557d60eeebe9fa695424a6e3930a8fd
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.setRequestMethod("GET");
InputStream is = InputStream();
reader =new BufferedReader(new InputStreamReader(is,"UTF-8"));
String strRead = null;
while((strRead = adLine())!= null){
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = String();
}catch(Exception e){
e.printStackTrace();
}
return result;
}
public static void main(String[] args){
/**
* @param urlAll
* :请求接⼝
* @param httpArg
* :参数
* @return 返回结果
*/
String httpUrl ="api.tianapi/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.setRequestMethod("GET");
InputStream is = InputStream();
reader =new BufferedReader(new InputStreamReader(is,"UTF-8"));
String strRead = null;
while((strRead = adLine())!= null){
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = String();
}catch(Exception e){
e.printStackTrace();
}
return result;
}
public static void main(String[] args){
/**
* @param urlAll
* :请求接⼝
* @param httpArg
* :参数
* @return 返回结果
*/
String httpUrl ="api.tianapi/txapi/ncovcity/index?key=d557d60eeebe9fa695424a6e3930a8fd"; String httpArg="date=2020-03-12";
System.out.println(request(httpUrl,httpArg));
}
}
测试结果
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论