public RequestDispatcher(Iterable<GrizzletHandler> grizzlets) { Map<String, Map<HttpMethod, GrizzletHandler>> modifiableHandlersMap = Maps.newHashMap(); for (GrizzletHandler handler : grizzlets) { Map<HttpMethod, GrizzletHandler> handlerByMethod = modifiableHandlersMap.get(handler.getPath()); if (handlerByMethod == null) { handlerByMethod = Maps.newEnumMap(HttpMethod.class); modifiableHandlersMap.put(handler.getPath(), handlerByMethod); } for (HttpMethod method : handler.getMethods()) { GrizzletHandler alreadyHandler = handlerByMethod.put(method, handler); if (alreadyHandler != null) { throw new IllegalArgumentException( "More than one handler detected for path='" + handler.getPath() + "', method='" + method.name() + '\''); } } } for (Map.Entry<String, Map<HttpMethod, GrizzletHandler>> entry : modifiableHandlersMap.entrySet()) { modifiableHandlersMap.put(entry.getKey(), Collections.unmodifiableMap(entry.getValue())); } handlers = ImmutableMap.copyOf(modifiableHandlersMap); }
private String getResponse(URL url) throws IOException { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(httpMethod.name()); conn.connect(); InputStream is = conn.getInputStream(); return Utils.readInput(is); }
private String generateSignature(Map<String, Object> params) { final String stringToSign = httpMethod.name() + "\n" + credentials.getApiHost().toLowerCase() + "\n" + path + "\n" + canonicalQueryString(params); return Utils.getHash(credentials.getSecretKey(), stringToSign); }
/** Set the (new) value of the {@code Access-Control-Request-Method} request header. */ public void setAccessControlRequestMethod(HttpMethod requestedMethod) { set(ACCESS_CONTROL_REQUEST_METHOD, requestedMethod.name()); }
private String execute(HttpMethod method, String url, Map<String, String> paramz) throws IOException { if (!(method.equals(HttpMethod.GET) || method.equals(HttpMethod.DELETE) || method.equals(HttpMethod.PUT) || method.equals(HttpMethod.POST)) || TextUtils.isEmpty(url)) { logger.error("Invalid request : {} | {}", method.name(), url); return null; } logger.trace("HTTP {} : {}", method.name(), url); BufferedInputStream bis = null; StringBuilder builder = new StringBuilder(); int buf_size = 50 * 1024; // read in chunks of 50 KB ByteArrayBuffer bab = new ByteArrayBuffer(buf_size); String query = getEncodedParameters(paramz); logger.trace("Query String : {}", query); HttpURLConnection conn = null; try { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) { HttpUriRequest req = null; switch (method) { case GET: case DELETE: url = paramz.size() > 0 ? url + "?" + query : url; if (method.equals(HttpMethod.GET)) { req = new HttpGet(url); } else if (method.equals(HttpMethod.DELETE)) { req = new HttpDelete(url); } break; case POST: case PUT: HttpEntity entity = TextUtils.isEmpty(query) ? null : new StringEntity(query); BasicHeader header = new BasicHeader(HTTP.CONTENT_ENCODING, "application/x-www-form-urlencoded"); if (method.equals(HttpMethod.PUT)) { HttpPut putr = new HttpPut(url); if (entity != null) { putr.setHeader(header); putr.setEntity(entity); req = putr; } } else if (method.equals(HttpMethod.POST)) { HttpPost postr = new HttpPost(url); if (entity != null) { postr.setHeader(header); postr.setEntity(entity); req = postr; } } } HttpResponse httpResponse = HttpManager.execute(req, Utils.DEV_ENV, version); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { logger.warn("HTTP request failed with status code: {}", statusCode); logger.warn(httpResponse.getStatusLine().getReasonPhrase()); throw new IOException("HTTP request failed with status code : " + statusCode); } bis = new BufferedInputStream(httpResponse.getEntity().getContent()); } else { if (method.equals(HttpMethod.GET) || method.equals(HttpMethod.DELETE)) { url = paramz.size() > 0 ? url + "?" + query : url; } URL uri = new URL(url); conn = (HttpURLConnection) uri.openConnection(); conn.setRequestProperty("User-Agent", userAgent + "/" + version); conn.setDoInput(true); conn.setReadTimeout(60 * 1000 /* milliseconds */); conn.setConnectTimeout(60 * 1000 /* milliseconds */); conn.setRequestMethod(method.name()); if (method.equals(HttpMethod.POST) || method.equals(HttpMethod.PUT)) { conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(query); writer.close(); os.close(); } int status = conn.getResponseCode(); if (status != HttpStatus.SC_OK) { logger.warn("HTTP request failed with status code: {}", status); logger.warn(conn.getResponseMessage()); throw new IOException("HTTP request failed with status code : " + status); } bis = new BufferedInputStream(conn.getInputStream()); } int read = 0; if (bis != null) { byte buffer[] = new byte[buf_size]; while ((read = bis.read(buffer, 0, buf_size)) != -1) { // builder.append(new String(buffer, "utf-8")); bab.append(buffer, 0, read); } builder.append(new String(bab.toByteArray(), "UTF-8")); } if (conn != null) conn.disconnect(); } catch (IOException e1) { e1.printStackTrace(); logger.error("HTTP request failed : {}", e1); throw e1; } return builder.toString(); }
public HttpURLConnection createHttpConnection( String theUrl, HttpMethod method, HttpMethod tunneledMethod, boolean apiKeyProtected, boolean sessionIdProtected, boolean headerAllowed) throws Exception { String query = (theUrl.indexOf('?') == -1) ? "" : theUrl.substring(theUrl.indexOf('?') + 1); if (apiKeyProtected) { if (query.contains(API_KEY) || query.contains(SIG) || query.contains(TIME)) throw new IllegalArgumentException( "URL to be secured must not contain " + "" + API_KEY + " or " + SIG + " or " + TIME + "!"); if (apiKey == null || secret == null) throw new IllegalArgumentException("APIKey or secret not found!"); } if (sessionIdProtected) { if (query.contains(SESSION_ID)) throw new IllegalArgumentException( "URL to be secured must not contain " + "" + SESSION_ID + "!"); if (sessionId == null) throw new IllegalArgumentException("SessionId not found!"); } String time = Long.toString(System.currentTimeMillis()); String sprdAuth = SPRD_AUTH + " "; if (headerAllowed) { if (apiKeyProtected) { sprdAuth += " " + API_KEY + "=\"" + apiKey + "\", " + DATA + "=\"" + calculateData(theUrl, method, tunneledMethod, time) + "\", " + SIG + "=\"" + calculateSignature(theUrl, method, tunneledMethod, time) + "\""; } if (sessionIdProtected) { if (apiKeyProtected) sprdAuth += "\", "; sprdAuth += " " + SESSION_ID + "=\"" + sessionId + "\""; } } else { if (apiKeyProtected || sessionIdProtected) theUrl = (theUrl.indexOf('?') != -1) ? theUrl : theUrl + "?"; if (apiKeyProtected) { if (theUrl.charAt(theUrl.length() - 1) != '?') theUrl += "&"; theUrl += API_KEY + "=" + apiKey + "&" + SIG + "=" + calculateSignature(theUrl, method, tunneledMethod, time) + "&" + TIME + "=" + time; } if (sessionIdProtected) { if (theUrl.charAt(theUrl.length() - 1) != '?') theUrl += "&"; theUrl += "&" + SESSION_ID + "=" + sessionId; } } log.info("Url is {} {}", method.name(), theUrl); if (tunneledMethod != null) { theUrl += (theUrl.indexOf("?") == -1) ? "?" : "&"; theUrl += "method=" + tunneledMethod.toString(); } HttpURLConnection connection = null; try { URL url = new URL(theUrl); connection = (HttpURLConnection) url.openConnection(); connection.setUseCaches(false); connection.setRequestMethod(method.name()); connection.setDoOutput(true); connection.setDoInput(true); connection.setConnectTimeout(10000); if (headerAllowed && (apiKeyProtected || sessionIdProtected)) { log.info(SPRD_AUTH + " header is " + sprdAuth); connection.setRequestProperty("Authorization", sprdAuth); } // connection.setRequestProperty("Content-Encoding", "gzip"); return connection; } catch (IOException e) { if (connection != null) connection.disconnect(); throw e; } }
public String toString() { return httpMethod.name() + ", " + path + ", " + target; }