blob: faf7d6ed32cc11ed9509951c153ce371f60d732b [file] [log] [blame]
Jonathan Hart61ba9372013-05-19 20:10:29 -07001package net.floodlightcontroller.bgproute;
2
3import java.io.BufferedReader;
4import java.io.IOException;
5import java.io.InputStreamReader;
6import java.net.HttpURLConnection;
7import java.net.MalformedURLException;
8import java.net.URL;
9
10import org.slf4j.Logger;
11import org.slf4j.LoggerFactory;
12
13
14public class RestClient {
15 protected static Logger log = LoggerFactory.getLogger(RestClient.class);
16
17 public static String get(String str) {
18 StringBuilder response = new StringBuilder();
19
20 try {
21
22 URL url = new URL(str);
23 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
24 conn.setRequestMethod("GET");
25 conn.setRequestProperty("Accept", "application/json");
26
27 if (conn.getResponseCode() != 200) {
28 throw new RuntimeException("Failed : HTTP error code : "
29 + conn.getResponseCode());
30 }
31
32 if (!conn.getContentType().equals("application/json")){
33 log.warn("The content received from {} is not json", str);
34 }
35
36 BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
37 String line;
38 while ((line = br.readLine()) != null) {
39 response.append(line);
40 }
41
42 br.close();
43 conn.disconnect();
44
45 } catch (MalformedURLException e) {
46 log.error("Malformed URL for GET request", e);
47 } catch (IOException e) {
48 log.warn("Couldn't connect remote REST server");
49 }
50
51 return response.toString();
52 }
53
54 public static void post (String str) {
55
56 try {
57 URL url = new URL(str);
58 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
59 conn.setDoOutput(true);
60 conn.setRequestMethod("POST");
61 conn.setRequestProperty("Content-Type", "application/json");
62
63 if (conn.getResponseCode() != 200) {
64 throw new RuntimeException("Failed : HTTP error code : "
65 + conn.getResponseCode());
66 }
67
68 conn.disconnect();
69
70 } catch (MalformedURLException e) {
71 log.error("Malformed URL for GET request", e);
72 } catch (IOException e) {
73 log.warn("Couldn't connect remote REST server");
74 }
75 }
76
77
78 public static void delete (String str) {
79
80 try {
81 URL url = new URL(str);
82 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
83 conn.setRequestMethod("DELETE");
84 conn.setRequestProperty("Accept", "application/json");
85
86
87 if (conn.getResponseCode() != 200) {
88 throw new RuntimeException("Failed : HTTP error code : "
89 + conn.getResponseCode());
90 }
91
92 conn.disconnect();
93
94 } catch (MalformedURLException e) {
95 log.error("Malformed URL for GET request", e);
96 } catch (IOException e) {
97 log.warn("Couldn't connect remote REST server");
98 }
99 }
100}