diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/utils/http/HttpUtils.java b/ruoyi-common/src/main/java/com/ruoyi/common/utils/http/HttpUtils.java index d50578915..5dd52496f 100644 --- a/ruoyi-common/src/main/java/com/ruoyi/common/utils/http/HttpUtils.java +++ b/ruoyi-common/src/main/java/com/ruoyi/common/utils/http/HttpUtils.java @@ -22,6 +22,7 @@ import org.slf4j.LoggerFactory; import com.ruoyi.common.constant.Constants; import com.ruoyi.common.utils.StringUtils; import org.springframework.http.MediaType; +import java.net.HttpURLConnection; /** * 通用http发送方法 @@ -72,12 +73,22 @@ public class HttpUtils String urlNameString = StringUtils.isNotBlank(param) ? url + "?" + param : url; log.info("sendGet - {}", urlNameString); URL realUrl = new URL(urlNameString); - URLConnection connection = realUrl.openConnection(); + HttpURLConnection connection = (HttpURLConnection)realUrl.openConnection(); connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"); connection.connect(); - in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType)); + + //获取状态码 + int code = connection.getResponseCode(); + System.out.println("ResponseCode="+code); + + if (code == 200) { + in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType)); + } else { + // HttpURLConnection 才有getErrorStream方法 + in = new BufferedReader(new InputStreamReader(connection.getErrorStream(), contentType)); + } String line; while ((line = in.readLine()) != null) { @@ -147,7 +158,7 @@ public class HttpUtils { log.info("sendPost - {}", url); URL realUrl = new URL(url); - URLConnection conn = realUrl.openConnection(); + HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection(); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"); @@ -158,7 +169,17 @@ public class HttpUtils out = new PrintWriter(conn.getOutputStream()); out.print(param); out.flush(); - in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8)); + + //获取状态码 + int code = conn.getResponseCode(); + System.out.println("ResponseCode="+code); + + if (code == 200) { + in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8)); + } else { + // HttpURLConnection 才有getErrorStream方法 + in = new BufferedReader(new InputStreamReader(conn.getErrorStream(), StandardCharsets.UTF_8)); + } String line; while ((line = in.readLine()) != null) {