-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSocketCommunication.java
75 lines (67 loc) · 2.49 KB
/
SocketCommunication.java
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import com.google.gson.stream.JsonReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.PriorityQueue;
import java.util.Queue;
/**
* Created by Carlos on 1/28/2017.
*/
public class SocketCommunication {
protected static final String CHARSET = "UTF-8";
protected static final String POST = "POST";
protected static final String PUT = "PUT";
protected static final String GET = "GET";
protected static final String HEAD = "HEAD";
/** Opens the connection with HTTPURLConnection
* @return the connection
* @exception IOException The exception is handled and will return null.
**/
protected static HttpURLConnection establishConnection(String url) {
URL resource;
try {
resource = new URL(url);
} catch (MalformedURLException m) {
System.err.println("No protocol is specified, or an unknown protocol is found, or parameter is null");
return null;
}
HttpURLConnection connection;
try {
connection = (HttpURLConnection) resource.openConnection();
} catch (IOException ie) {
System.err.println("An I/O error occurs while opening the connection.");
return null;
}
return connection;
}
/** Writes the data to the server. Hence, it writes the request.
**/
protected static void writeToOutputStream(HttpURLConnection connection, String data) {
OutputStreamWriter out;
try {
out = new OutputStreamWriter(connection.getOutputStream());
out.write(data);
out.flush();
out.close();
} catch (IOException ie) {
System.err.println("An I/O error occured while opening the output.\n" + ie.getMessage());
return;
}
}
/** Reads the JSONResponse
*/
protected static Queue readJSONResponse(HttpURLConnection connection) {
try {
JsonReader objectReader = new JsonReader(new InputStreamReader(connection.getInputStream(), CHARSET));
PriorityQueue result = (PriorityQueue) ResponseParser.parseJSON(objectReader);
objectReader.close();
return result;
} catch (IOException ie) {
System.err.println("An I/O error occurs while opening the input\n" + ie.getMessage());
return null;
}
}
}