1 package org.opendaylight.mwtn.base.database;
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.io.OutputStream;
6 import java.net.HttpURLConnection;
8 import java.net.URLConnection;
10 import org.json.JSONObject;
11 import org.slf4j.Logger;
12 import org.slf4j.LoggerFactory;
15 public class HtDatabaseWebAPIClient {
17 private static Logger LOG = LoggerFactory.getLogger(HtDatabaseWebAPIClient.class);
18 private static final int BUFSIZE = 1024;
19 private static final String CHARSET = "UTF-8";
20 private final String host;
21 private final int port;
22 public HtDatabaseWebAPIClient()
24 this.host="http://localhost";
28 public String sendRequest(String uri,String method,JSONObject body) throws IOException
30 LOG.debug("try to send request with uri="+uri+" as method="+method);
32 LOG.trace("body:"+body.toString());
33 String surl=String.format("%s:%d%s",this.host,this.port,uri);
34 URL url = new URL(surl);
35 URLConnection http = url.openConnection();
36 ((HttpURLConnection) http).setRequestMethod(method);
37 http.setDoOutput(true);
38 http.setRequestProperty("Content-Type", "application/json");
39 byte[] buffer = new byte[BUFSIZE];
40 int len = 0, lensum = 0;
42 // Send the message to destination
43 if(!method.equals("GET"))
45 try (OutputStream output = http.getOutputStream()) {
46 output.write(body.toString().getBytes(CHARSET));
49 int responseCode = ((HttpURLConnection) http).getResponseCode();
52 if (responseCode >= 200 && responseCode < 300)
53 response = http.getInputStream();
56 response = ((HttpURLConnection) http).getErrorStream();
58 http.getInputStream();
64 len = response.read(buffer, 0, BUFSIZE);
68 sresponse+=new String(buffer,0,len,CHARSET);
73 LOG.debug("response is null");
74 LOG.debug("ResponseCode: " + responseCode);
75 LOG.trace("Response: " + sresponse);