You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
|
package Tools.Crawler;
|
|
|
|
|
|
|
|
|
|
import cn.hutool.http.HttpRequest;
|
|
|
|
|
|
|
|
|
|
public class Util {
|
|
|
|
|
|
|
|
|
|
// 默认超时时间(毫秒)
|
|
|
|
|
private static final int DEFAULT_TIMEOUT = 5000;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 发送GET请求
|
|
|
|
|
*
|
|
|
|
|
* @param url 请求URL
|
|
|
|
|
* @return 响应内容
|
|
|
|
|
*/
|
|
|
|
|
public static String doGet(String url) {
|
|
|
|
|
int retries = 3;
|
|
|
|
|
while (retries > 0) {
|
|
|
|
|
try {
|
|
|
|
|
return HttpRequest.get(url)
|
|
|
|
|
.timeout(DEFAULT_TIMEOUT)
|
|
|
|
|
.execute()
|
|
|
|
|
.body();
|
|
|
|
|
} catch (Exception e) {
|
|
|
|
|
System.out.println("调用失败,正在重试!");
|
|
|
|
|
retries--;
|
|
|
|
|
if (retries == 0) {
|
|
|
|
|
throw new RuntimeException("请求失败,已重试3次", e);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return null; // 这个返回语句实际上不会被执行到,但需要为了编译通过
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 发送POST请求
|
|
|
|
|
*
|
|
|
|
|
* @param url 请求URL
|
|
|
|
|
* @param body 请求体
|
|
|
|
|
* @return 响应内容
|
|
|
|
|
*/
|
|
|
|
|
public static String doPost(String url, String body) {
|
|
|
|
|
int retries = 3;
|
|
|
|
|
while (retries > 0) {
|
|
|
|
|
try {
|
|
|
|
|
return HttpRequest.post(url)
|
|
|
|
|
.header("Accept", "application/json")
|
|
|
|
|
.timeout(DEFAULT_TIMEOUT)
|
|
|
|
|
.body(body)
|
|
|
|
|
.execute()
|
|
|
|
|
.body();
|
|
|
|
|
} catch (Exception e) {
|
|
|
|
|
System.out.println("调用失败,正在重试!");
|
|
|
|
|
retries--;
|
|
|
|
|
if (retries == 0) {
|
|
|
|
|
throw new RuntimeException("请求失败,已重试3次", e);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return null; // 这个返回语句实际上不会被执行到,但需要为了编译通过
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|