コード例 #1
0
  private CloseableHttpClient generateClient(Site site) {
    HttpClientBuilder httpClientBuilder =
        HttpClients.custom().setConnectionManager(connectionManager);
    if (site != null && site.getUserAgent() != null) {
      httpClientBuilder.setUserAgent(site.getUserAgent());
    } else {
      httpClientBuilder.setUserAgent("");
    }
    if (site == null || site.isUseGzip()) {
      httpClientBuilder.addInterceptorFirst(
          new HttpRequestInterceptor() {

            public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
              if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip");
              }
            }
          });
    }
    SocketConfig socketConfig =
        SocketConfig.custom().setSoKeepAlive(true).setTcpNoDelay(true).build();
    httpClientBuilder.setDefaultSocketConfig(socketConfig);
    if (site != null) {
      httpClientBuilder.setRetryHandler(
          new DefaultHttpRequestRetryHandler(site.getRetryTimes(), true));
    }
    generateCookie(httpClientBuilder, site);
    return httpClientBuilder.build();
  }
コード例 #2
0
ファイル: HTTPSession.java プロジェクト: msdsoftware/thredds
 /**
  * Called primarily from HTTPMethod to do the bulk of the execution. Assumes HTTPMethod has
  * inserted its headers into request.
  *
  * @param method
  * @param methoduri
  * @param rb
  * @return Request+Response pair
  * @throws HTTPException
  */
 ExecState execute(HTTPMethod method, URI methoduri, RequestBuilder rb) throws HTTPException {
   this.execution = new ExecState();
   this.requestURI = methoduri;
   AuthScope methodscope = HTTPAuthUtil.uriToAuthScope(methoduri);
   AuthScope target = HTTPAuthUtil.authscopeUpgrade(this.scope, methodscope);
   synchronized (this) { // keep coverity happy
     // Merge Settings;
     Settings merged = HTTPUtil.merge(globalsettings, localsettings);
     if (!this.cachevalid) {
       RequestConfig.Builder rcb = RequestConfig.custom();
       this.cachedconfig = configureRequest(rcb, merged);
       HttpClientBuilder cb = HttpClients.custom();
       configClient(cb, merged);
       setAuthenticationAndProxy(cb);
       this.cachedclient = cb.build();
       rb.setConfig(this.cachedconfig);
       this.cachevalid = true;
     }
   }
   this.execution.request = (HttpRequestBase) rb.build();
   try {
     HttpHost targethost = HTTPAuthUtil.authscopeToHost(target);
     this.execution.response =
         cachedclient.execute(targethost, this.execution.request, this.sessioncontext);
   } catch (IOException ioe) {
     throw new HTTPException(ioe);
   }
   return this.execution;
 }
コード例 #3
0
ファイル: ClientSimple.java プロジェクト: uhurue/tuva
  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;
      }
    }
  }
コード例 #4
0
  public static String apiRequest(Request request, String... paramValues) {
    if (httpClient == null) {
      httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
    }
    RequestBuilder reqBuilder;
    HttpUriRequest get, post;
    switch (request.type) {
      case GET:
        reqBuilder = RequestBuilder.get("http://naturesnap.net/" + request.getEndpoint());
        for (int i = 0; i < request.getParams().length; i++) {
          reqBuilder.addParameter(request.getParams()[i], paramValues[i]);
        }
        get = reqBuilder.build();
        try {
          CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(get);
          HttpEntity entity = response.getEntity();
          String content = IOUtils.toString(entity.getContent(), "UTF-8");
          response.close();
          return content;
        } catch (ClientProtocolException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
        break;
      case POST:
        reqBuilder = RequestBuilder.post().setUri("http://naturesnap.net/" + request.getEndpoint());
        for (int i = 0; i < request.getParams().length; i++) {
          reqBuilder.addParameter(request.getParams()[i], paramValues[i]);
        }
        post = reqBuilder.build();
        try {
          CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(post);
          HttpEntity entity = response.getEntity();
          String content = IOUtils.toString(entity.getContent(), "UTF-8");
          response.close();
          return content;
        } catch (ClientProtocolException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
        break;
      case FILE:
        HttpPost postFile = new HttpPost("http://naturesnap.net/" + request.getEndpoint());
        File file = new File(request.getParams()[0]);
        FileBody fileBody = new FileBody(file);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("filename", fileBody);
        builder.addTextBody("uploadForm", "Upload");
        builder.addTextBody("latitude", request.getParams()[1]);
        builder.addTextBody("longitude", request.getParams()[2]);
        builder.addTextBody("groupName", "");
        builder.addTextBody("description", "");
        HttpEntity entity = builder.build();
        postFile.setEntity(entity);
        try {
          HttpResponse response = httpClient.execute(postFile);
          return IOUtils.toString(response.getEntity().getContent(), "UTF-8");
        } catch (Exception e) {

        }
        break;
      default:
        // Error
        break;
    }

    return "";
  }