Java读取网址信息
今天的需求是根据接口获取JSON数据并存入,之前只会前端用
Ajax
或者Axios
去处理显示出来没想过后端也要拿,没有思路于是查找,发现都是基础以前用的还是太少了,特此总结,后续有需要再补充。
1.读取get请求,无需参数
public static String get(String urlStr) {// 设置返回信息String message = "";try {// 请求网址URL url = new URL(urlStr);// 开启连接HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 设置连接方式connection.setRequestMethod("GET");// 连接超时connection.setConnectTimeout(5 * 1000);// 连接connection.connect();// 从输入流读取返回内容InputStream inputStream = connection.getInputStream();InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");BufferedReader bufferedReader = new BufferedReader(inputStreamReader);String str = null;StringBuffer buffer = new StringBuffer();while ((str = bufferedReader.readLine()) != null) {buffer.append(str);}message = buffer.toString();// 释放资源bufferedReader.close();inputStreamReader.close();inputStream.close();// 关闭连接connection.disconnect();} catch (Exception e) {e.printStackTrace();}return message;
}
测试
public static void main(String[] args) {String URL="https://www.cnblogs.com/";String result = get(URL);System.out.println(result);
}