Beispiel #1
0
 private void SetupHTTPConnectionParams(HttpUriRequest method) {
   HttpConnectionParams.setConnectionTimeout(method.getParams(), CONNECTION_TIMEOUT_MS);
   HttpConnectionParams.setSoTimeout(method.getParams(), SOCKET_TIMEOUT_MS);
   // mClient.setHttpRequestRetryHandler(requestRetryHandler);
   method.addHeader("Accept-Encoding", "gzip, deflate");
   method.addHeader("Accept-Charset", "UTF-8,*;q=0.5");
 }
  /**
   * Authenticate with the chosen bridge
   *
   * @param ip, the ip address of the bridge you want to authenticate with
   * @return the username of the hue bridge, that has been placed on the white list
   */
  private String authWithBridge(String ip)
      throws URISyntaxException, MalformedURLException, UnsupportedEncodingException {

    URI uri = new URL("http://" + ip + "/api").toURI();

    DefaultHttpClient client = new DefaultHttpClient();
    HttpUriRequest request = new HttpPost(uri);

    JSONObject obj = new JSONObject();
    try {
      obj.put("devicetype", "OpenRemoteController");
    } catch (JSONException e) {
      logger.error("JSONExceptionn when creating json object", e);
    }

    StringEntity data = new StringEntity(obj.toString(), "UTF-8");

    ((HttpPost) request).setEntity(data);
    String resp = "";
    HttpResponse response = null;
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    request.addHeader("User-Agent", "OpenRemoteController");
    request.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

    request.addHeader("Content-Type", "applicaion/json");

    try {
      response = client.execute(request);
      resp = responseHandler.handleResponse(response);
    } catch (ClientProtocolException e) {
      logger.error("ClientProtocolException when executing HTTP method", e);
    } catch (IOException e) {
      logger.error("IOException when executing HTTP method", e);
    } finally {
      try {
        if ((response != null) && (response.getEntity() != null)) {
          response.getEntity().consumeContent();
        }
      } catch (IOException ignored) {
      }
      client.getConnectionManager().shutdown();
    }

    JSONObject jsonResponse = null;
    String jsonUsername = "";
    try {
      jsonResponse = new JSONArray(resp.toString()).getJSONObject(0).getJSONObject("success");
      jsonUsername = jsonResponse.getString("username");
    } catch (JSONException e) {
      logger.error("JSONException when reading returned json", e);
    }
    return jsonUsername;
  }
  /**
   * @param method
   * @param httpclient
   * @return
   * @throws IOException
   * @throws ClientProtocolException
   */
  private HttpResponse execute(HttpUriRequest method, HttpClient httpclient)
      throws IOException, ClientProtocolException {
    if (needAuth()) {
      return HttpClientUtils.executeWithBasicAuth(method, httpclient);
    }

    if (soTimeout > 0) {
      HttpConnectionParams.setSoTimeout(method.getParams(), soTimeout);
    }

    return httpclient.execute(method);
  }
Beispiel #4
0
 @Override
 public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
     throws IOException, AuthFailureError {
   HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders);
   addHeaders(httpRequest, additionalHeaders);
   addHeaders(httpRequest, request.getHeaders());
   onPrepareRequest(httpRequest);
   HttpParams httpParams = httpRequest.getParams();
   int timeoutMs = request.getTimeoutMs();
   HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
   HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);
   return mClient.execute(httpRequest);
 }
 @Override
 public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
     throws IOException, AuthFailureError {
   HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders);
   addHeaders(httpRequest, additionalHeaders);
   addHeaders(httpRequest, request.getHeaders());
   onPrepareRequest(httpRequest);
   HttpParams httpParams = httpRequest.getParams();
   int timeoutMs = request.getTimeoutMs();
   // TODO: Reevaluate this connection timeout based on more wide-scale
   // data collection and possibly different for wifi vs. 3G.
   HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
   HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);
   return mClient.execute(httpRequest);
 }
Beispiel #6
0
  public HttpResponse performMultiPartRequest(
      Request<?> request, Map<String, String> additionalHeaders)
      throws IOException, AuthFailureError {
    HttpUriRequest httpRequest = createMultiPartRequest(request, additionalHeaders);
    addHeaders(httpRequest, additionalHeaders);
    addHeaders(httpRequest, request.getHeaders());
    HttpParams httpParams = httpRequest.getParams();
    int timeoutMs = request.getTimeoutMs();
    // TODO: Reevaluate this connection timeout based on more wide-scale
    // data collection and possibly different for wifi vs. 3G.
    HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
    HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);

    /* Make a thread safe connection manager for the client */
    HttpClient httpClient = new DefaultHttpClient(httpParams);

    return httpClient.execute(httpRequest);
  }
Beispiel #7
0
  public HttpResponse performMultiPartRequest(
      Request<?> request, Map<String, String> additionalHeaders)
      throws IOException, AuthFailureError {
    HttpUriRequest httpRequest = createMultiPartRequest(request, additionalHeaders);
    addHeaders(httpRequest, additionalHeaders);
    addHeaders(httpRequest, request.getHeaders());
    HttpParams httpParams = httpRequest.getParams();
    int timeoutMs = request.getTimeoutMs();

    if (timeoutMs != -1) {
      HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);
    }

    /* Make a thread safe connection manager for the client */
    HttpClient httpClient = new DefaultHttpClient(httpParams);

    return httpClient.execute(httpRequest);
  }
Beispiel #8
0
  public Either<IOException, HttpResponse> execRequest(HttpUriRequest httpReq, String acceptType) {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpReq.setHeader("accept", acceptType);
    for (Header header : getHeaders()) {
      httpReq.setHeader(header);
    }

    try {
      HttpResponse resp = httpClient.execute(httpReq);
      Log.i(
          TAG,
          String.format(
              "%s %s %s => %d",
              httpReq.getRequestLine().getMethod(),
              httpReq.getRequestLine().getUri(),
              httpReq.getParams(),
              resp.getStatusLine().getStatusCode()));
      return new Right<IOException, HttpResponse>(resp);
    } catch (IOException e) {
      return new Left<IOException, HttpResponse>(e);
    }
  }
 /**
  * {@inheritDoc} <br>
  * <br>
  * The default implementation always sets a 30 second timeout.
  */
 @Override
 public void setRequestTimeout(HttpUriRequest request) {
   HttpParams reqParams = request.getParams();
   HttpConnectionParams.setSoTimeout(reqParams, DEFAULT_TIMEOUT_MILLIS);
   HttpConnectionParams.setConnectionTimeout(reqParams, DEFAULT_TIMEOUT_MILLIS);
 }
  public HttpResponse fetch(org.apache.shindig.gadgets.http.HttpRequest request)
      throws GadgetException {
    HttpUriRequest httpMethod = null;
    Preconditions.checkNotNull(request);
    final String methodType = request.getMethod();

    final org.apache.http.HttpResponse response;
    final long started = System.currentTimeMillis();

    // Break the request Uri to its components:
    Uri uri = request.getUri();
    if (StringUtils.isEmpty(uri.getAuthority())) {
      throw new GadgetException(
          GadgetException.Code.INVALID_USER_DATA,
          "Missing domain name for request: " + uri,
          HttpServletResponse.SC_BAD_REQUEST);
    }
    if (StringUtils.isEmpty(uri.getScheme())) {
      throw new GadgetException(
          GadgetException.Code.INVALID_USER_DATA,
          "Missing schema for request: " + uri,
          HttpServletResponse.SC_BAD_REQUEST);
    }
    String[] hostparts = StringUtils.splitPreserveAllTokens(uri.getAuthority(), ':');
    int port = -1; // default port
    if (hostparts.length > 2) {
      throw new GadgetException(
          GadgetException.Code.INVALID_USER_DATA,
          "Bad host name in request: " + uri.getAuthority(),
          HttpServletResponse.SC_BAD_REQUEST);
    }
    if (hostparts.length == 2) {
      try {
        port = Integer.parseInt(hostparts[1]);
      } catch (NumberFormatException e) {
        throw new GadgetException(
            GadgetException.Code.INVALID_USER_DATA,
            "Bad port number in request: " + uri.getAuthority(),
            HttpServletResponse.SC_BAD_REQUEST);
      }
    }

    String requestUri = uri.getPath();
    // Treat path as / if set as null.
    if (uri.getPath() == null) {
      requestUri = "/";
    }
    if (uri.getQuery() != null) {
      requestUri += '?' + uri.getQuery();
    }

    // Get the http host to connect to.
    HttpHost host = new HttpHost(hostparts[0], port, uri.getScheme());

    try {
      if ("POST".equals(methodType) || "PUT".equals(methodType)) {
        HttpEntityEnclosingRequestBase enclosingMethod =
            ("POST".equals(methodType)) ? new HttpPost(requestUri) : new HttpPut(requestUri);

        if (request.getPostBodyLength() > 0) {
          enclosingMethod.setEntity(
              new InputStreamEntity(request.getPostBody(), request.getPostBodyLength()));
        }
        httpMethod = enclosingMethod;
      } else if ("GET".equals(methodType)) {
        httpMethod = new HttpGet(requestUri);
      } else if ("HEAD".equals(methodType)) {
        httpMethod = new HttpHead(requestUri);
      } else if ("DELETE".equals(methodType)) {
        httpMethod = new HttpDelete(requestUri);
      }
      for (Map.Entry<String, List<String>> entry : request.getHeaders().entrySet()) {
        httpMethod.addHeader(entry.getKey(), StringUtils.join(entry.getValue(), ','));
      }

      // Disable following redirects.
      if (!request.getFollowRedirects()) {
        httpMethod.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);
      }

      // HttpClient doesn't handle all cases when breaking url (specifically '_' in domain)
      // So lets pass it the url parsed:
      response = FETCHER.execute(host, httpMethod);

      if (response == null) {
        throw new IOException("Unknown problem with request");
      }

      long now = System.currentTimeMillis();
      if (now - started > slowResponseWarning) {
        slowResponseWarning(request, started, now);
      }

      return makeResponse(response);

    } catch (Exception e) {
      long now = System.currentTimeMillis();

      // Find timeout exceptions, respond accordingly
      if (TIMEOUT_EXCEPTIONS.contains(e.getClass())) {
        LOG.info(
            "Timeout for "
                + request.getUri()
                + " Exception: "
                + e.getClass().getName()
                + " - "
                + e.getMessage()
                + " - "
                + (now - started)
                + "ms");
        return HttpResponse.timeout();
      }

      LOG.log(
          Level.INFO,
          "Got Exception fetching " + request.getUri() + " - " + (now - started) + "ms",
          e);

      // Separate shindig error from external error
      throw new GadgetException(
          GadgetException.Code.INTERNAL_SERVER_ERROR,
          e,
          HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } finally {
      // cleanup any outstanding resources..
      if (httpMethod != null)
        try {
          httpMethod.abort();
        } catch (UnsupportedOperationException e) {
          // ignore
        }
    }
  }
 public static HttpResponse execute(Session paramSession, HttpUriRequest paramHttpUriRequest, int paramInt)
 {
   HttpClient localHttpClient = updatedHttpClient(paramSession);
   paramSession.setRequestTimeout(paramHttpUriRequest);
   if (paramInt >= 0) {
     HttpConnectionParams.setSoTimeout(paramHttpUriRequest.getParams(), paramInt);
   }
   boolean bool = isRequestRepeatable(paramHttpUriRequest);
   Object localObject1 = null;
   paramInt = 0;
   for (;;)
   {
     Object localObject2;
     if (paramInt >= 5)
     {
       localObject2 = localObject1;
       label46:
       if (localObject2 != null) {
         break label129;
       }
     }
     try
     {
       throw new DropboxIOException("Apache HTTPClient encountered an error. No response, try again.");
     }
     catch (SSLException paramSession)
     {
       throw new DropboxSSLException(paramSession);
       try
       {
         localObject2 = localHttpClient.execute(paramHttpUriRequest);
         localObject1 = localObject2;
       }
       catch (NullPointerException localNullPointerException)
       {
         for (;;) {}
       }
       localObject2 = localObject1;
       if (localObject1 != null) {
         break label46;
       }
       updateClientProxy(localHttpClient, paramSession);
       if (!bool) {
         throw new DropboxProxyChangeException();
       }
     }
     catch (IOException paramSession)
     {
       throw new DropboxIOException(paramSession);
       paramInt += 1;
       continue;
       paramInt = ((HttpResponse)localObject2).getStatusLine().getStatusCode();
       if ((paramInt != 200) && (paramInt != 206)) {
         parseAsJSON((HttpResponse)localObject2);
       }
       return (HttpResponse)localObject2;
     }
     catch (OutOfMemoryError paramSession)
     {
       label129:
       throw new DropboxException(paramSession);
     }
   }
 }
Beispiel #12
0
  protected HttpUriRequest prepareRequest(
      int method, String baseUri, String path, HttpEntity paramsEntity) {
    URI uri = null;
    HttpUriRequest request = null;

    try {
      StringBuffer sb = new StringBuffer();

      if (method == GET) {
        sb.append(baseUri);
        sb.append(path);

        if (paramsEntity != null) {
          sb.append("?");
          try {
            IOTricks.copyStreamToStringBuffer(paramsEntity.getContent(), sb);
          } catch (IllegalStateException e) {
            Log.e(TAG, "Error preparing url", e);
            return null;
          } catch (IOException e) {
            Log.e(TAG, "Error preparing url", e);
            return null;
          }
        }
        uri = new URI(sb.toString());

        if (SimpleHttpClient.debug) Log.i(TAG, "GET " + uri.toString());
        if (SimpleHttpClient.debug && paramsEntity != null)
          Log.i(TAG, "-- " + IOTricks.StreamToString(paramsEntity.getContent()));

        request = new HttpGet(uri);
      } else if (method == POST) {
        sb.append(baseUri);
        sb.append(path);

        uri = new URI(sb.toString());

        if (SimpleHttpClient.debug) Log.i(TAG, "POST " + uri.toString());
        if (SimpleHttpClient.debug && paramsEntity != null)
          try {
            Log.i(TAG, "-- " + IOTricks.StreamToString(paramsEntity.getContent()));
          } catch (Exception e) {
          }

        request = new HttpPost(uri);

        request.getParams().setBooleanParameter("http.protocol.expect-continue", false);

        if (paramsEntity != null) {
          request.addHeader(paramsEntity.getContentType());
          ((HttpPost) request).setEntity(paramsEntity);
        } else {
          request.addHeader("Content-Type", "application/x-www-form-urlencoded");
        }
      } else if (method == PUT) {
        sb.append(baseUri);
        sb.append(path);

        uri = new URI(sb.toString());

        if (SimpleHttpClient.debug) Log.i(TAG, "PUT " + uri.toString());
        if (SimpleHttpClient.debug && paramsEntity != null)
          Log.i(TAG, "-- " + IOTricks.StreamToString(paramsEntity.getContent()));

        request = new HttpPut(uri);

        request.addHeader("Content-Type", "application/x-www-form-urlencoded");
        request.getParams().setBooleanParameter("http.protocol.expect-continue", false);

        if (paramsEntity != null) {
          request.addHeader(paramsEntity.getContentType());
          ((HttpPut) request).setEntity(paramsEntity);
        } else {
          request.addHeader("Content-Type", "application/x-www-form-urlencoded");
        }
      } else if (method == DELETE) {
        sb.append(baseUri);
        sb.append(path);

        if (paramsEntity != null) {
          sb.append("?");
          try {
            IOTricks.copyStreamToStringBuffer(paramsEntity.getContent(), sb);
          } catch (IllegalStateException e) {
            Log.e(TAG, "Error preparing url", e);
            return null;
          } catch (IOException e) {
            Log.e(TAG, "Error preparing url", e);
            return null;
          }
        }
        uri = new URI(sb.toString());

        if (SimpleHttpClient.debug) Log.i(TAG, "DELETE " + uri.toString());
        if (SimpleHttpClient.debug && paramsEntity != null)
          Log.i(TAG, "-- " + IOTricks.StreamToString(paramsEntity.getContent()));

        request = new HttpDelete(uri);
      }

      request.addHeader("User-Agent", userAgent());
    } catch (URISyntaxException e) {
      Log.e(TAG, "Invalid URI for " + baseUri + " / " + path + " ...", e);
    } catch (IllegalStateException e) {
      Log.e(TAG, "Illegal State for " + baseUri + " / " + path + " ...", e);
    } catch (IOException e) {
      Log.e(TAG, "IOException for " + baseUri + " / " + path + " ...", e);
    }

    return request;
  }