Exemple #1
0
 private String sendBasic(HttpRequestBase request) throws HttpException {
   try {
     HttpResponse response = httpClient.execute(request);
     HttpEntity entity = response.getEntity();
     String body = "";
     if (entity != null) {
       body = EntityUtils.toString(entity, UTF_8);
       if (entity.getContentType() == null) {
         body = new String(body.getBytes(ISO_8859_1), UTF_8);
       }
     }
     int code = response.getStatusLine().getStatusCode();
     if (code < 200 || code >= 300) {
       throw new Exception(String.format(" code : '%s' , body : '%s'", code, body));
     }
     return body;
   } catch (Exception ex) {
     throw new HttpException(
         "Fail to send "
             + request.getMethod()
             + " request to url "
             + request.getURI()
             + ", "
             + ex.getMessage(),
         ex);
   } finally {
     request.releaseConnection();
   }
 }
 /** @return {@link InputStream} from a {@link HttpResponse} */
 InputStream getStream(HttpResponse response) {
   try {
     return response.getEntity().getContent();
   } catch (Exception e) {
     log.error("Error reading response. " + e.getMessage());
     throw new CouchDbException(e);
   }
 }
Exemple #3
0
  public static final void main(String[] args) throws Exception {
    String uri = args[0];
    int reqNum = Integer.parseInt(args[1]);
    int reqTerm = Integer.parseInt(args[2]);

    try {
      // new ClientSimple().request1(uri, reqNum, reqTerm);
      new ClientSimple().request2(uri, reqNum, reqTerm);
    } catch (Exception e) {
      System.out.println("ERROR:" + e.getMessage());
    }
  }
  public @Nullable <T> T get(Class<T> classType, @Nonnull URI uri)
      throws CloudException, InternalException {
    InputStream responseAsStream = getAsStream(provider.getContext().getAccountNumber(), uri);

    if (responseAsStream == null) {
      logger.info("Unable to perform HTTP GET at following resource: " + uri.toString());
      return null;
    }
    try {
      JAXBContext context = JAXBContext.newInstance(classType);
      Unmarshaller u = context.createUnmarshaller();
      return (T) u.unmarshal(responseAsStream);
    } catch (Exception ex) {
      logger.error(ex.getMessage());
      throw new InternalException(ex);
    }
  }
Exemple #5
0
  public void request1(String uri, int reqNum, int reqTerm) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    if (reqNum == 0) {
      System.out.println(
          String.format("request to %s infinite times with term '%d' ms", uri, reqTerm));
    } else {
      System.out.println(
          String.format("request to %s '%d' times with term '%d' ms", uri, reqNum, reqTerm));
    }

    int i = 0, tick = 0;
    HttpGet httpGet = new HttpGet(uri);
    CloseableHttpResponse response;
    HttpEntity entity;

    while (true) {
      usleep(reqTerm);
      tick = (int) (Math.random() * 10) % 2;
      if (tick == 0) {
        continue;
      }
      System.out.println("request " + httpGet.getURI());
      response = httpclient.execute(httpGet);
      System.out.println("--> response status  = " + response.getStatusLine());
      // response handler
      try {
        entity = response.getEntity();
        EntityUtils.consume(entity);
      } catch (Exception e) {
        System.out.println("  --> http fail:" + e.getMessage());
      } finally {
        // Thread.sleep(5000); //테스트에만 썼다. close 지연시키려고.
        response.close();
      }

      System.out.println("----------------------------------------");
      if (reqNum != 0 && reqNum < ++i) {
        break;
      }
    }
  }
  /** @return {@link DefaultHttpClient} instance. */
  private HttpClient createHttpClient(CouchDbProperties props) {
    DefaultHttpClient httpclient = null;
    try {
      SchemeSocketFactory ssf = null;
      if (props.getProtocol().equals("https")) {
        TrustManager trustManager =
            new X509TrustManager() {
              public void checkClientTrusted(X509Certificate[] chain, String authType)
                  throws CertificateException {}

              public void checkServerTrusted(X509Certificate[] chain, String authType)
                  throws CertificateException {}

              public X509Certificate[] getAcceptedIssuers() {
                return null;
              }
            };
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(null, new TrustManager[] {trustManager}, null);
        ssf = new SSLSocketFactory(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        SSLSocket socket = (SSLSocket) ssf.createSocket(null);
        socket.setEnabledCipherSuites(new String[] {"SSL_RSA_WITH_RC4_128_MD5"});
      } else {
        ssf = PlainSocketFactory.getSocketFactory();
      }
      SchemeRegistry schemeRegistry = new SchemeRegistry();
      schemeRegistry.register(new Scheme(props.getProtocol(), props.getPort(), ssf));
      PoolingClientConnectionManager ccm = new PoolingClientConnectionManager(schemeRegistry);
      httpclient = new DefaultHttpClient(ccm);
      host = new HttpHost(props.getHost(), props.getPort(), props.getProtocol());
      context = new BasicHttpContext();
      // Http params
      httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
      httpclient
          .getParams()
          .setParameter(CoreConnectionPNames.SO_TIMEOUT, props.getSocketTimeout());
      httpclient
          .getParams()
          .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, props.getConnectionTimeout());
      int maxConnections = props.getMaxConnections();
      if (maxConnections != 0) {
        ccm.setMaxTotal(maxConnections);
        ccm.setDefaultMaxPerRoute(maxConnections);
      }
      if (props.getProxyHost() != null) {
        HttpHost proxy = new HttpHost(props.getProxyHost(), props.getProxyPort());
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
      }
      // basic authentication
      if (props.getUsername() != null && props.getPassword() != null) {
        httpclient
            .getCredentialsProvider()
            .setCredentials(
                new AuthScope(props.getHost(), props.getPort()),
                new UsernamePasswordCredentials(props.getUsername(), props.getPassword()));
        props.clearPassword();
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(host, basicAuth);
        context.setAttribute(ClientContext.AUTH_CACHE, authCache);
      }
      // request interceptor
      httpclient.addRequestInterceptor(
          new HttpRequestInterceptor() {
            public void process(final HttpRequest request, final HttpContext context)
                throws IOException {
              if (log.isInfoEnabled()) {
                RequestLine requestLine = request.getRequestLine();
                try {
                  log.info(
                      ">> "
                          + (new StringBuilder())
                              .append(">> ")
                              .append(requestLine.getMethod())
                              .append(" ")
                              .append(urlCodec.decode(requestLine.getUri()))
                              .toString());
                } catch (DecoderException e) {
                  log.error(e, e);
                }
              }
            }
          });
      // response interceptor
      httpclient.addResponseInterceptor(
          new HttpResponseInterceptor() {
            public void process(final HttpResponse response, final HttpContext context)
                throws IOException {
              validate(response);
              if (log.isInfoEnabled())
                log.info("<< Status: " + response.getStatusLine().getStatusCode());
            }
          });
    } catch (Exception e) {
      log.error("Error Creating HTTP client. " + e.getMessage());
      throw new IllegalStateException(e);
    }
    return httpclient;
  }