From 362c1af8bcafedd15dcd81e72fb6888b93e5000b Mon Sep 17 00:00:00 2001
From: zj <1772600164@qq.com>
Date: Tue, 14 May 2024 16:23:58 +0800
Subject: [PATCH] 1
---
src/main/java/com/nq/utils/http/HttpRequest.java | 34 ++++++++++++----------------------
1 files changed, 12 insertions(+), 22 deletions(-)
diff --git a/src/main/java/com/nq/utils/http/HttpRequest.java b/src/main/java/com/nq/utils/http/HttpRequest.java
index 586fbbc..a41fafa 100644
--- a/src/main/java/com/nq/utils/http/HttpRequest.java
+++ b/src/main/java/com/nq/utils/http/HttpRequest.java
@@ -68,50 +68,40 @@
/*
*抓數據專用,
- *signature:授權碼
- * timestamp:時間戳
* url
*/
public static String doGrabGet(String url) throws Exception {
- // Request URL: http://gateway.jinyi999.cn/rjhy-news/api/1/tcy/news/hotlist?columnCodes=cjyw&appCode=tcy&showPermission=0&limit=20&hasContent=0&pageNo=1
URL localURL = new URL(url);
URLConnection connection = localURL.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
- httpURLConnection.setConnectTimeout(6000);
- InputStream inputStream = null;
- InputStreamReader inputStreamReader = null;
- BufferedReader reader = null;
-
+ httpURLConnection.setConnectTimeout(12000); // 设置连接超时时间
+ httpURLConnection.setReadTimeout(12000); // 设置读取超时时间
StringBuffer resultBuffer = new StringBuffer();
- String tempLine = null;
if (httpURLConnection.getResponseCode() >= 300) {
+ throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
}
- try {
- inputStream = httpURLConnection.getInputStream();
- inputStreamReader = new InputStreamReader(inputStream);
- reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
+ try (InputStream inputStream = httpURLConnection.getInputStream();
+ InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
+ BufferedReader reader = new BufferedReader(inputStreamReader)) {
+
+ String tempLine;
while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
}
+
} finally {
- if (reader != null) {
- reader.close();
- }
- if (inputStreamReader != null) {
- inputStreamReader.close();
- }
- if (inputStream != null) {
- inputStream.close();
- }
+ httpURLConnection.disconnect(); // 断开连接,释放资源
}
+
return resultBuffer.toString();
}
+
public static String doPost(String url, Map<String, String> params) throws Exception {
HttpPost httpPost = new HttpPost(url);
--
Gitblit v1.9.3