From dc970724ce7ef1ca48e5a945885baf2ad366974a Mon Sep 17 00:00:00 2001 From: pjhmizn49 Date: Fri, 13 Dec 2024 14:41:40 +0800 Subject: [PATCH] ADD file via upload --- .../com/example/flower/unit/HttpUtils.java | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 flower_back/src/main/java/com/example/flower/unit/HttpUtils.java diff --git a/flower_back/src/main/java/com/example/flower/unit/HttpUtils.java b/flower_back/src/main/java/com/example/flower/unit/HttpUtils.java new file mode 100644 index 0000000..aa74ef8 --- /dev/null +++ b/flower_back/src/main/java/com/example/flower/unit/HttpUtils.java @@ -0,0 +1,71 @@ +package com.example.flower.unit; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.nio.charset.StandardCharsets; + +public class HttpUtils { + public static String getRequest(String httpurl) { + + HttpURLConnection connection = null; + InputStream is = null; + BufferedReader br = null; + String result = null;// 返回结果字符串 + try { + // 创建远程url连接对象 + URL url = new URL(httpurl); + // 通过远程url连接对象打开一个连接,强转成httpURLConnection类 + connection = (HttpURLConnection) url.openConnection(); + // 设置连接方式:get + connection.setRequestMethod("GET"); + // 设置连接主机服务器的超时时间:15000毫秒 + connection.setConnectTimeout(15000); + // 设置读取远程返回的数据时间:60000毫秒 + connection.setReadTimeout(60000); + // 发送请求 + connection.connect(); + // 通过connection连接,获取输入流 + if (connection.getResponseCode() == 200) { + is = connection.getInputStream(); + // 封装输入流is,并指定字符集 + br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)); + // 存放数据 + StringBuilder sbf = new StringBuilder(); + String temp = null; + while ((temp = br.readLine()) != null) { + sbf.append(temp); + sbf.append("\r\n"); + } + result = sbf.toString(); + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + // 关闭资源 + if (null != br) { + try { + br.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (null != is) { + try { + is.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (connection != null) { + connection.disconnect();// 关闭远程连接 + } + } + + return result; + } +}