Sending an api request through Http GET @param command command name @param params command query parameters in a HashMap @return http request response string
(String command, HashMap<String, String> params)
| 49 | * @return http request response string |
| 50 | */ |
| 51 | protected String sendRequest(String command, HashMap<String, String> params) { |
| 52 | try { |
| 53 | // Construct query string |
| 54 | StringBuilder sBuilder = new StringBuilder(); |
| 55 | sBuilder.append("command="); |
| 56 | sBuilder.append(command); |
| 57 | if (params != null && params.size() > 0) { |
| 58 | Iterator<String> keys = params.keySet().iterator(); |
| 59 | while (keys.hasNext()) { |
| 60 | String key = keys.next(); |
| 61 | sBuilder.append("&"); |
| 62 | sBuilder.append(key); |
| 63 | sBuilder.append("="); |
| 64 | sBuilder.append(URLEncoder.encode(params.get(key), "UTF-8")); |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | // Construct request url |
| 69 | String reqUrl = rootUrl + "?" + sBuilder.toString(); |
| 70 | |
| 71 | // Send Http GET request |
| 72 | URL url = new URL(reqUrl); |
| 73 | HttpURLConnection conn = (HttpURLConnection)url.openConnection(); |
| 74 | conn.setRequestMethod("GET"); |
| 75 | |
| 76 | if (!command.equals("login") && cookieToSent != null) { |
| 77 | // add the cookie to a request |
| 78 | conn.setRequestProperty("Cookie", cookieToSent); |
| 79 | } |
| 80 | conn.connect(); |
| 81 | |
| 82 | if (command.equals("login")) { |
| 83 | // if it is login call, store cookie |
| 84 | String headerName = null; |
| 85 | for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) { |
| 86 | if (headerName.equals("Set-Cookie")) { |
| 87 | String cookie = conn.getHeaderField(i); |
| 88 | cookie = cookie.substring(0, cookie.indexOf(";")); |
| 89 | String cookieName = cookie.substring(0, cookie.indexOf("=")); |
| 90 | String cookieValue = cookie.substring(cookie.indexOf("=") + 1, cookie.length()); |
| 91 | cookieToSent = cookieName + "=" + cookieValue; |
| 92 | } |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | // Get the response |
| 97 | StringBuilder response = new StringBuilder(); |
| 98 | BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); |
| 99 | String line; |
| 100 | try { |
| 101 | while ((line = rd.readLine()) != null) { |
| 102 | response.append(line); |
| 103 | } |
| 104 | } catch (EOFException ex) { |
| 105 | // ignore this exception |
| 106 | System.out.println("EOF exception due to java bug"); |
| 107 | } |
| 108 | rd.close(); |
no test coverage detected