推荐常用接口网址:
极速数据:https://www.jisuapi.com/api/
代码如下:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; public class Test { public static void main(String[] args) throws IOException { //1、将发送到服务器的中文,进行url编码 String content = URLEncoder.encode("北京天气", "utf-8"); //2、准备网址,创建一个url对象
//注意kksb,key:密钥;number:手机号;code:验证码
//String urlStr = "https://itdage.com/kksb/kksbsms?key=kksb&number=16612345679&code=666"; String urlStr = "https://api.jisuapi.com/iqa/query?appkey=62958a3a6ef3c56d&question=" + content; URL url = new URL(urlStr); //3、建立连接,通过url,打开网络连接,并得到连接对象conn //3.1正常访问,未加浏览器标识,这时候会导致被一些api拦截,识别为恶意攻击的请求 //URLConnection conn = url.openConnection(); //3.2加了浏览器标识的访问,模拟浏览器发请求("User-Agent"可以自行百度) HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.addRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1"); //4、通过连接对象,获取输入流is InputStream is = conn.getInputStream(); //5、将输入流is,装饰为一次能读取一行的缓冲字符输入流 BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)); //6、读取内容 String text = br.readLine(); System.out.println(text); //7、关闭流 br.close(); } }