1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.esigate.server;
17
18 import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
19 import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
20
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.net.HttpURLConnection;
24 import java.net.SocketException;
25 import java.net.URL;
26
27 import org.apache.commons.io.IOUtils;
28
29
30
31
32
33
34
35
36
37 public final class Http {
38
39 private Http() {
40 }
41
42 public static class Response {
43 private final String body;
44 private final int code;
45
46 public Response(int code) {
47 this(code, "");
48 }
49
50 public Response(int code, String body) {
51 this.code = code;
52 this.body = body;
53 }
54 }
55
56
57
58
59
60
61
62
63
64 public static Response doGET(String uri) {
65 return http("GET", uri);
66 }
67
68 static Response http(String method, String uri) {
69 try {
70 URL url = new URL(uri);
71 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
72 conn.setRequestMethod(method);
73 Object content = conn.getContent();
74
75 if (content instanceof InputStream) {
76 return new Response(conn.getResponseCode(), IOUtils.toString((InputStream) content, "UTF-8"));
77 } else if (content instanceof String) {
78 return new Response(conn.getResponseCode(), (String) content);
79 } else {
80 return new Response(conn.getResponseCode(), "unknown");
81 }
82
83 } catch (SocketException e) {
84 return new Response(SC_NOT_FOUND);
85 } catch (IOException e) {
86 return new Response(SC_INTERNAL_SERVER_ERROR);
87 }
88 }
89
90
91
92
93
94
95
96
97 public static Response doPOST(String uri) {
98 return http("POST", uri);
99 }
100
101 }