Java-封装Http操作

Java中经常需要进行网络请求,最常用的就是Get和Post请求。

Java中定义了URLConnection可用于Http访问,如果结合线程池,可以实现多个请求异步访问,但是同步返回结果,可用于类似爬虫等应用。

下文介绍如何结合线程池对Http请求进行封装。

1.首先,定义HttpReq,封装请求的路径,参数以及类型。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class HttpReq {
public String url;
public String param;
public HttpMethod method;
public enum HttpMethod {
GET, POST
}
public HttpReq(String url, String param, HttpMethod method) {
super();
this.url = url;
this.param = param;
this.method = method;
}
}

2.其次,定义HttpResq,对请求的结果进行封装。

1
2
3
4
5
6
7
8
9
10
11
12
public class HttpResp {
public HttpReq req;
public String result;
public HttpResp(HttpReq req, String result) {
super();
this.req = req;
this.result = result;
}
}

3.定义HttpCallable,用于具体地处理HttpReq,并返回HttpResp。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class HttpCallable implements Callable<Object> {
private HttpReq req;
public HttpCallable(HttpReq req){
this.req = req;
}
@Override
public Object call() throws Exception {
return response(req);
}
private static HttpResp response(HttpReq req){
String result = "";
PrintWriter out = null;
BufferedReader in = null;
try {
URL url = null;
URLConnection connection = null;
switch(req.method){
case GET:
url = new URL(req.url + "?" + req.param);
connection = url.openConnection();
connection.connect();
break;
case POST:
url = new URL(req.url);
connection = url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
out = new PrintWriter(connection.getOutputStream());
out.print(req.param);
out.flush();
break;
default:
return new HttpResp(req, result);
}
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while (null != (line = in.readLine()))
result += line;
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
if(null != out)
out.close();
if(null != in)
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return new HttpResp(req, result);
}
}

4.定义工具类HttpUtil,利用线程池处理请求。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class HttpUtil {
private HttpUtil(){
super();
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static ArrayList<HttpResp> HttpResp(ArrayList<HttpReq> reqList){
ArrayList<HttpResp> results = new ArrayList<HttpResp>();
if(null != reqList && !reqList.isEmpty()){
try{
int taskSize = reqList.size();
ExecutorService pool = Executors.newFixedThreadPool(taskSize);
List<Future> list = new ArrayList<Future>();
for (int i = 0; i < taskSize; ++i) {
Callable c = new HttpCallable(reqList.get(i));
Future f = pool.submit(c);
list.add(f);
}
pool.shutdown();
for (Future f : list) {
results.add((HttpResp) f.get());
}
}catch(Exception e){
e.printStackTrace();
}
}
return results;
}
}
YI wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!