提交 | 用户 | 时间
|
71e81e
|
1 |
package cn.stylefeng.guns.timer.jobhandler; |
懒 |
2 |
|
|
3 |
import com.xxl.job.core.biz.model.ReturnT; |
|
4 |
import com.xxl.job.core.handler.IJobHandler; |
|
5 |
import com.xxl.job.core.handler.annotation.JobHandler; |
|
6 |
import com.xxl.job.core.log.XxlJobLogger; |
|
7 |
|
|
8 |
import java.io.BufferedReader; |
|
9 |
import java.io.InputStreamReader; |
|
10 |
import java.net.HttpURLConnection; |
|
11 |
import java.net.URL; |
|
12 |
|
|
13 |
/** |
|
14 |
* 跨平台Http任务 |
|
15 |
* |
|
16 |
* @author xuxueli 2018-09-16 03:48:34 |
|
17 |
*/ |
|
18 |
@JobHandler(value = "httpJobHandler") |
|
19 |
public class HttpJobHandler extends IJobHandler { |
|
20 |
|
|
21 |
@Override |
|
22 |
public ReturnT<String> execute(String param) throws Exception { |
|
23 |
|
|
24 |
// request |
|
25 |
HttpURLConnection connection = null; |
|
26 |
BufferedReader bufferedReader = null; |
|
27 |
try { |
|
28 |
// connection |
|
29 |
URL realUrl = new URL(param); |
|
30 |
connection = (HttpURLConnection) realUrl.openConnection(); |
|
31 |
|
|
32 |
// connection setting |
|
33 |
connection.setRequestMethod("GET"); |
|
34 |
connection.setDoOutput(true); |
|
35 |
connection.setDoInput(true); |
|
36 |
connection.setUseCaches(false); |
|
37 |
connection.setReadTimeout(5 * 1000); |
|
38 |
connection.setConnectTimeout(3 * 1000); |
|
39 |
connection.setRequestProperty("connection", "Keep-Alive"); |
|
40 |
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); |
|
41 |
connection.setRequestProperty("Accept-Charset", "application/json;charset=UTF-8"); |
|
42 |
|
|
43 |
// do connection |
|
44 |
connection.connect(); |
|
45 |
|
|
46 |
//Map<String, List<String>> map = connection.getHeaderFields(); |
|
47 |
|
|
48 |
// valid StatusCode |
|
49 |
int statusCode = connection.getResponseCode(); |
|
50 |
if (statusCode != 200) { |
|
51 |
throw new RuntimeException("Http Request StatusCode(" + statusCode + ") Invalid."); |
|
52 |
} |
|
53 |
|
|
54 |
// result |
|
55 |
bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream())); |
|
56 |
StringBuilder result = new StringBuilder(); |
|
57 |
String line; |
|
58 |
while ((line = bufferedReader.readLine()) != null) { |
|
59 |
result.append(line); |
|
60 |
} |
|
61 |
String responseMsg = result.toString(); |
|
62 |
|
|
63 |
XxlJobLogger.log(responseMsg); |
|
64 |
return SUCCESS; |
|
65 |
} catch (Exception e) { |
|
66 |
XxlJobLogger.log(e); |
|
67 |
return FAIL; |
|
68 |
} finally { |
|
69 |
try { |
|
70 |
if (bufferedReader != null) { |
|
71 |
bufferedReader.close(); |
|
72 |
} |
|
73 |
if (connection != null) { |
|
74 |
connection.disconnect(); |
|
75 |
} |
|
76 |
} catch (Exception e2) { |
|
77 |
XxlJobLogger.log(e2); |
|
78 |
} |
|
79 |
} |
|
80 |
|
|
81 |
} |
|
82 |
|
|
83 |
} |