Java 类org.apache.http.message.BasicHeader 实例源码

项目:apollo-custom    文件:RestTemplateFactory.java   
public void afterPropertiesSet() throws UnsupportedEncodingException {
  Collection<Header> defaultHeaders = new ArrayList<Header>();
  Header header = new BasicHeader("Authorization",
      "Basic " + BaseEncoding.base64().encode("apollo:".getBytes("UTF-8")));
  defaultHeaders.add(header);

  BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  credentialsProvider.setCredentials(AuthScope.ANY,
      new UsernamePasswordCredentials("apollo", ""));
  CloseableHttpClient httpClient =
      HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider)
          .setDefaultHeaders(defaultHeaders).build();


  restTemplate = new RestTemplate(httpMessageConverters.getConverters());
  HttpComponentsClientHttpRequestFactory requestFactory =
      new HttpComponentsClientHttpRequestFactory(httpClient);
  requestFactory.setConnectTimeout(portalConfig.connectTimeout());
  requestFactory.setReadTimeout(portalConfig.readTimeout());

  restTemplate.setRequestFactory(requestFactory);
}
项目:codescene-jenkins-plugin    文件:DeltaAnalysis.java   
private HttpPost createRequestFor(final DeltaAnalysisRequest payload) throws URISyntaxException {
    final CodeSceneUser user = config.user();

    final Header authorization = new BasicHeader("Authorization", "Basic " + user.asBase64Encoded());

    HttpPost codeSceneRequest = new HttpPost(config.codeSceneUrl().toURI());
    codeSceneRequest.addHeader(authorization);

    StringEntity requestEntity = new StringEntity(
            payload.asJson().toString(),
            ContentType.APPLICATION_JSON);
    codeSceneRequest.setEntity(requestEntity);

    return codeSceneRequest;
}
项目:GitHub    文件:HttpHeaderParserTest.java   
@Test public void parseCaseInsensitive() {

        long now = System.currentTimeMillis();

        Header[] headersArray = new Header[5];
        headersArray[0] = new BasicHeader("eTAG", "Yow!");
        headersArray[1] = new BasicHeader("DATE", rfc1123Date(now));
        headersArray[2] = new BasicHeader("expires", rfc1123Date(now + ONE_HOUR_MILLIS));
        headersArray[3] = new BasicHeader("cache-control", "public, max-age=86400");
        headersArray[4] = new BasicHeader("content-type", "text/plain");

        Map<String, String> headers = BasicNetwork.convertHeaders(headersArray);
        NetworkResponse response = new NetworkResponse(0, null, headers, false);
        Cache.Entry entry = HttpHeaderParser.parseCacheHeaders(response);

        assertNotNull(entry);
        assertEquals("Yow!", entry.etag);
        assertEqualsWithin(now + ONE_DAY_MILLIS, entry.ttl, ONE_MINUTE_MILLIS);
        assertEquals(entry.softTtl, entry.ttl);
        assertEquals("ISO-8859-1", HttpHeaderParser.parseCharset(headers));
    }
项目:GitHub    文件:HttpHeaderParserTest.java   
@Test public void parseCaseInsensitive() {

        long now = System.currentTimeMillis();

        Header[] headersArray = new Header[5];
        headersArray[0] = new BasicHeader("eTAG", "Yow!");
        headersArray[1] = new BasicHeader("DATE", rfc1123Date(now));
        headersArray[2] = new BasicHeader("expires", rfc1123Date(now + ONE_HOUR_MILLIS));
        headersArray[3] = new BasicHeader("cache-control", "public, max-age=86400");
        headersArray[4] = new BasicHeader("content-type", "text/plain");

        Map<String, String> headers = BasicNetwork.convertHeaders(headersArray);
        NetworkResponse response = new NetworkResponse(0, null, headers, false);
        Cache.Entry entry = HttpHeaderParser.parseCacheHeaders(response);

        assertNotNull(entry);
        assertEquals("Yow!", entry.etag);
        assertEqualsWithin(now + ONE_DAY_MILLIS, entry.ttl, ONE_MINUTE_MILLIS);
        assertEquals(entry.softTtl, entry.ttl);
        assertEquals("ISO-8859-1", HttpHeaderParser.parseCharset(headers));
    }
项目:educational-plugin    文件:EduStepicClient.java   
static boolean isTokenUpToDate(@NotNull String token) {
  if (token.isEmpty()) return false;

  final List<BasicHeader> headers = new ArrayList<>();
  headers.add(new BasicHeader("Authorization", "Bearer " + token));
  headers.add(new BasicHeader("Content-type", EduStepicNames.CONTENT_TYPE_APP_JSON));
  CloseableHttpClient httpClient = getBuilder().setDefaultHeaders(headers).build();

  try {
    final StepicWrappers.AuthorWrapper wrapper =
      getFromStepic(EduStepicNames.CURRENT_USER, StepicWrappers.AuthorWrapper.class, httpClient);
    if (wrapper != null && !wrapper.users.isEmpty()) {
      StepicUser user = wrapper.users.get(0);
      return user != null && !user.isGuest();
    }
    else {
      throw new IOException(wrapper == null ? "Got a null current user" : "Got an empty wrapper");
    }
  }
  catch (IOException e) {
    LOG.warn(e.getMessage());
    return false;
  }
}
项目:elasticsearch_my    文件:RequestLoggerTests.java   
public void testResponseWarnings() throws Exception {
    HttpHost host = new HttpHost("localhost", 9200);
    HttpUriRequest request = randomHttpRequest(new URI("/index/type/_api"));
    int numWarnings = randomIntBetween(1, 5);
    StringBuilder expected = new StringBuilder("request [").append(request.getMethod()).append(" ").append(host)
            .append("/index/type/_api] returned ").append(numWarnings).append(" warnings: ");
    Header[] warnings = new Header[numWarnings];
    for (int i = 0; i < numWarnings; i++) {
        String warning = "this is warning number " + i;
        warnings[i] = new BasicHeader("Warning", warning);
        if (i > 0) {
            expected.append(",");
        }
        expected.append("[").append(warning).append("]");
    }
    assertEquals(expected.toString(), RequestLogger.buildWarningMessage(request, host, warnings));
}
项目:groupsio-api-java    文件:BaseResource.java   
/**
 * Get a valid {@link HttpClient} to use, with a valid token.
 * 
 * @param login
 * @return
 */
private CloseableHttpClient getHttpClient(final Boolean login, final HttpUriRequest request)
{
    final HttpClientBuilder builder = HttpClientBuilder.create();
    String key;
    // if (apiClient.getApiToken() == null || apiClient.getApiToken())
    if (login)
    {
        key = apiClient.getApiKey();
    }
    else
    {
        key = apiClient.getApiToken();
    }
    key += ":";
    final byte[] credentials = Base64.encodeBase64(key.getBytes(StandardCharsets.UTF_8));
    final BasicHeader authHeader = new BasicHeader("Authorization", "Basic " + new String(credentials, StandardCharsets.UTF_8));
    request.addHeader(authHeader);
    return builder.build();
}
项目:Codeforces    文件:HttpHeaderParserTest.java   
@Test public void parseCaseInsensitive() {

        long now = System.currentTimeMillis();

        Header[] headersArray = new Header[5];
        headersArray[0] = new BasicHeader("eTAG", "Yow!");
        headersArray[1] = new BasicHeader("DATE", rfc1123Date(now));
        headersArray[2] = new BasicHeader("expires", rfc1123Date(now + ONE_HOUR_MILLIS));
        headersArray[3] = new BasicHeader("cache-control", "public, max-age=86400");
        headersArray[4] = new BasicHeader("content-type", "text/plain");

        Map<String, String> headers = BasicNetwork.convertHeaders(headersArray);
        NetworkResponse response = new NetworkResponse(0, null, headers, false);
        Cache.Entry entry = HttpHeaderParser.parseCacheHeaders(response);

        assertNotNull(entry);
        assertEquals("Yow!", entry.etag);
        assertEqualsWithin(now + ONE_DAY_MILLIS, entry.ttl, ONE_MINUTE_MILLIS);
        assertEquals(entry.softTtl, entry.ttl);
        assertEquals("ISO-8859-1", HttpHeaderParser.parseCharset(headers));
    }
项目:letv    文件:rcccrr.java   
private Header[] b044Cьь044Cь044C(String str) {
    try {
        Header[] headerArr = new Header[5];
        try {
            headerArr[0] = new BasicHeader("content-type", "application/x-amz-json-1.0");
            headerArr[1] = new BasicHeader("host", "dynamodb.us-west-2.amazonaws.com");
            if (((b0427Ч0427Ч0427Ч + b04270427ЧЧ0427Ч) * b0427Ч0427Ч0427Ч) % bЧЧ0427Ч0427Ч != bЧ0427ЧЧ0427Ч) {
                b0427Ч0427Ч0427Ч = 86;
                bЧ0427ЧЧ0427Ч = b0427ЧЧЧ0427Ч();
            }
            headerArr[2] = new BasicHeader("x-amz-date", getYYYYMMDDTHHMMSSZ());
            headerArr[3] = new BasicHeader("x-amz-security-token", str);
            headerArr[4] = new BasicHeader("x-amz-target", "DynamoDB_20120810.PutItem");
            return headerArr;
        } catch (Exception e) {
            throw e;
        }
    } catch (Exception e2) {
        throw e2;
    }
}
项目:letv    文件:rcccrr.java   
private HttpPost bььь044Cь044C(String str, String str2, HttpPost httpPost) {
    try {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("AWS4-HMAC-SHA256 ").append("Credential=").append(str).append("/").append(getYYYYMMDD()).append("/").append(b041B041BЛЛЛ041B).append("/").append(bЛЛ041BЛЛ041B).append("/").append("aws4_request").append(",");
        stringBuilder.append("SignedHeaders=").append(new crrcrc().getSignedHeaders(this.b041BЛЛ041BЛ041B)).append(",");
        try {
            stringBuilder.append("Signature=").append(str2);
            String str3 = b041BЛЛЛЛ041B;
            StringBuilder stringBuilder2 = new StringBuilder();
            String str4 = "POST Authorization String:\n";
            if (((b0427Ч0427Ч0427Ч + b04270427ЧЧ0427Ч) * b0427Ч0427Ч0427Ч) % bЧЧ0427Ч0427Ч != bЧ0427ЧЧ0427Ч) {
                b0427Ч0427Ч0427Ч = b0427ЧЧЧ0427Ч();
                bЧ0427ЧЧ0427Ч = b0427ЧЧЧ0427Ч();
            }
            Log.d(str3, stringBuilder2.append(str4).append(stringBuilder.toString()).toString());
            httpPost.addHeader(new BasicHeader(HttpRequest.HEADER_AUTHORIZATION, stringBuilder.toString()));
            return httpPost;
        } catch (Exception e) {
            throw e;
        }
    } catch (Exception e2) {
        throw e2;
    }
}
项目:Huochexing12306    文件:HttpHelper.java   
public synchronized String get(Collection<BasicHeader> headers, String url) {
        String strResult = null;
        HttpGet httpGet = new HttpGet(url);
        setHeaders(headers);
        L.i("get request url:" + url);
        HttpResponse response;
        try {
            response = mHttpClient.execute(httpGet);
            L.i("CustomHttpClient get:" + String.valueOf(response.getStatusLine()));
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                strResult = getContentStr(response.getEntity().getContent());
//              L.i("get response string:" + strResult);
            }
        }catch (Exception e) {
            e.printStackTrace();
            L.i("get fail");
        }
        return strResult;
    }
项目:Equella    文件:AbstractRestApiTest.java   
protected HttpResponse execute(HttpUriRequest request, boolean consume, String token)
    throws ClientProtocolException, IOException
{
    if( token != null )
    {
        final Header tokenHeader = new BasicHeader("X-Authorization", token);
        request.setHeader(tokenHeader);
    }
    request.setHeader("X-Autotest-Key", context.getFullName(""));
    HttpResponse response = getClient().execute(request);
    if( consume )
    {
        EntityUtils.consume(response.getEntity());
    }
    return response;
}
项目:cyberduck    文件:OAuth2RequestInterceptor.java   
@Override
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    if(tokens.isExpired()) {
        try {
            tokens = this.refresh(tokens);
        }
        catch(BackgroundException e) {
            log.warn(String.format("Failure refreshing OAuth 2 tokens. %s", e.getDetail()));
            throw new IOException(e);
        }
    }
    if(StringUtils.isNotBlank(tokens.getAccessToken())) {
        if(log.isInfoEnabled()) {
            log.info(String.format("Authorizing service request with OAuth2 access token %s", tokens.getAccessToken()));
        }
        request.removeHeaders(HttpHeaders.AUTHORIZATION);
        request.addHeader(new BasicHeader(HttpHeaders.AUTHORIZATION, String.format("Bearer %s", tokens.getAccessToken())));
    }
}
项目:cyberduck    文件:DAVWriteFeature.java   
@Override
public HttpResponseOutputStream<String> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
    final List<Header> headers = new ArrayList<Header>();
    if(status.isAppend()) {
        final HttpRange range = HttpRange.withStatus(status);
        // Content-Range entity-header is sent with a partial entity-body to specify where
        // in the full entity-body the partial body should be applied.
        final String header = String.format("bytes %d-%d/%d", range.getStart(), range.getEnd(),
                status.getOffset() + status.getLength());
        if(log.isDebugEnabled()) {
            log.debug(String.format("Add range header %s for file %s", header, file));
        }
        headers.add(new BasicHeader(HttpHeaders.CONTENT_RANGE, header));
    }
    if(expect) {
        if(status.getLength() > 0L) {
            headers.add(new BasicHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE));
        }
    }
    return this.write(file, headers, status);
}
项目:http-progressive-download-examples    文件:VideoResourceIT.java   
@Test
public void returnVideoPartAccordingToRange() throws Exception {
  byte[] expectedVideo = readVideoFileBytes(Fixtures.videoId);
  long min = 1024L * 1024L;
  long max = 1024L * 2048L;
  Range expectedRange = Range.closed(min, max);
  byte[] expectedVideoPart = sliceFile(expectedVideo, expectedRange);

  Response response = client.getVideo(Fixtures.videoId, new BasicHeader("Range", format("bytes=%d-%d", min, max)));

  assertThat(response.getStatus(), equalTo(206));
  byte[] actualVideoPart = response.readEntity(byte[].class);
  assertTrue(Arrays.equals(actualVideoPart, expectedVideoPart));
  verifyPartialContentHeaders(response, expectedRange, expectedVideo.length);
  httpDateFormat.parse(response.getHeaderString("Last-Modified"));
}
项目:http-progressive-download-examples    文件:VideoResourceIT.java   
@Test
public void returnVideoPartRespectingEndOfFileForRangeWithoutMaxValue() throws Exception {
  byte[] expectedVideo = readVideoFileBytes(Fixtures.videoId);
  long max = expectedVideo.length;
  long min = max - 1000L;
  Range expectedRange = Range.leftClosed(min, max);
  byte[] expectedVideoPart = sliceFile(expectedVideo, expectedRange);

  Response response = client.getVideo(Fixtures.videoId, new BasicHeader("Range", format("bytes=%d-", min)));

  assertThat(response.getStatus(), equalTo(206));
  byte[] actualVideoPart = response.readEntity(byte[].class);
  assertTrue(Arrays.equals(actualVideoPart, expectedVideoPart));
  verifyPartialContentHeaders(response, expectedRange, expectedVideo.length);
  httpDateFormat.parse(response.getHeaderString("Last-Modified"));
}
项目:http-progressive-download-examples    文件:VideoResourceIT.java   
@Test
public void returnVideoPartWhenIfModifiedSincePreconditionIsTrue() throws Exception {
  File video = videoFilePath(Fixtures.videoId).toFile();
  String ifModifiedSince = httpDateFormat.format(video.lastModified() - 1);
  long min = 1024L * 1024L;
  long max = 1024L * 2048L;
  Range expectedRange = Range.closed(min, max);

  Response response = client.getVideo(Fixtures.videoId,
      new BasicHeader("Range", format("bytes=%d-%d", min, max)),
      new BasicHeader("If-Modified-Since", ifModifiedSince));

  response.close();
  assertThat(response.getStatus(), equalTo(206));
  verifyPartialContentHeaders(response, expectedRange, video.length());
  assertThat(httpDateFormat.parse(response.getHeaderString("Last-Modified")).getTime(), equalTo(video.lastModified()));
}
项目:http-progressive-download-examples    文件:VideoResourceIT.java   
@Test
public void returnVideoPartWhenIfRangePreconditionIsTrue() throws Exception {
  File video = videoFilePath(Fixtures.videoId).toFile();
  String ifRangeLastModified = httpDateFormat.format(video.lastModified());
  long min = 1024L * 1024L;
  long max = 1024L * 2048L;
  Range expectedRange = Range.closed(min, max);

  Response response = client.getVideo(Fixtures.videoId,
      new BasicHeader("Range", format("bytes=%d-%d", min, max)),
      new BasicHeader("If-Range", ifRangeLastModified));

  response.close();
  assertThat(response.getStatus(), equalTo(206));
  verifyPartialContentHeaders(response, expectedRange, video.length());
  assertThat(httpDateFormat.parse(response.getHeaderString("Last-Modified")).getTime(),
      equalTo(video.lastModified()));
}
项目:http-progressive-download-examples    文件:VideoResourceIT.java   
@Test
public void returnFullVideoWhenIfRangePreconditionIsFalse() throws Exception {
  File video = videoFilePath(Fixtures.videoId).toFile();
  String ifRangeLastModified = httpDateFormat.format(video.lastModified() - 1);
  long min = 1024L * 1024L;
  long max = 1024L * 2048L;

  Response response = client.getVideo(Fixtures.videoId,
      new BasicHeader("Range", format("bytes=%d-%d", min, max)),
      new BasicHeader("If-Range", ifRangeLastModified));

  response.close();
  assertThat(response.getStatus(), equalTo(200));
  assertThat(response.getHeaderString("Accept-Ranges"), equalTo("bytes"));
  assertThat(httpDateFormat.parse(response.getHeaderString("Last-Modified")).getTime(),
      equalTo(video.lastModified()));
}
项目:teasy    文件:CookiesService.java   
public void addHttpCookieFromResponseToHeader(final List<Header> headers, final HttpResponse httpResponse) {
    String cookieValue = "";
    for (Header header : httpResponse.getHeaders("Set-Cookie")) {
        List<HttpCookie> httpCookies = HttpCookie.parse(header.getValue());
        for (HttpCookie httpCookie : httpCookies) {
            if (!cookieValue.isEmpty()) {
                cookieValue += "; ";
            }
            cookieValue += httpCookie.getName() + "=" + httpCookie.getValue();
        }
    }
    headers.add(new BasicHeader("Cookie", cookieValue));
}
项目:Cable-Android    文件:LegacyMmsConnection.java   
protected List<Header> getBaseHeaders() {
  final String                number    = TelephonyUtil.getManager(context).getLine1Number(); ;

  return new LinkedList<Header>() {{
    add(new BasicHeader("Accept", "*/*, application/vnd.wap.mms-message, application/vnd.wap.sic"));
    add(new BasicHeader("x-wap-profile", "http://www.google.com/oha/rdf/ua-profile-kila.xml"));
    add(new BasicHeader("Content-Type", "application/vnd.wap.mms-message"));
    add(new BasicHeader("x-carrier-magic", "http://magic.google.com"));
    if (!TextUtils.isEmpty(number)) {
      add(new BasicHeader("x-up-calling-line-id", number));
      add(new BasicHeader("X-MDN", number));
    }
  }};
}
项目:PeSanKita-android    文件:LegacyMmsConnection.java   
protected List<Header> getBaseHeaders() {
  final String                number    = TelephonyUtil.getManager(context).getLine1Number(); ;

  return new LinkedList<Header>() {{
    add(new BasicHeader("Accept", "*/*, application/vnd.wap.mms-message, application/vnd.wap.sic"));
    add(new BasicHeader("x-wap-profile", "http://www.google.com/oha/rdf/ua-profile-kila.xml"));
    add(new BasicHeader("Content-Type", "application/vnd.wap.mms-message"));
    add(new BasicHeader("x-carrier-magic", "http://magic.google.com"));
    if (!TextUtils.isEmpty(number)) {
      add(new BasicHeader("x-up-calling-line-id", number));
      add(new BasicHeader("X-MDN", number));
    }
  }};
}
项目:educational-plugin    文件:EduStepicAuthorizedClient.java   
@NotNull
private static CloseableHttpClient createInitializedClient(@NotNull String accessToken) {
  final List<BasicHeader> headers = new ArrayList<>();
  headers.add(new BasicHeader("Authorization", "Bearer " + accessToken));
  headers.add(new BasicHeader("Content-type", EduStepicNames.CONTENT_TYPE_APP_JSON));
  return getBuilder().setDefaultHeaders(headers).build();
}
项目:airgram    文件:HurlStack.java   
@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion,
            connection.getResponseCode(), connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) {
        response.setEntity(entityFromConnection(connection));
    }
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }
    return response;
}
项目:elasticsearch_my    文件:TransportReindexAction.java   
/**
 * Build the {@link RestClient} used for reindexing from remote clusters.
 * @param remoteInfo connection information for the remote cluster
 * @param taskId the id of the current task. This is added to the thread name for easier tracking
 * @param threadCollector a list in which we collect all the threads created by the client
 */
static RestClient buildRestClient(RemoteInfo remoteInfo, long taskId, List<Thread> threadCollector) {
    Header[] clientHeaders = new Header[remoteInfo.getHeaders().size()];
    int i = 0;
    for (Map.Entry<String, String> header : remoteInfo.getHeaders().entrySet()) {
        clientHeaders[i] = new BasicHeader(header.getKey(), header.getValue());
    }
    return RestClient.builder(new HttpHost(remoteInfo.getHost(), remoteInfo.getPort(), remoteInfo.getScheme()))
            .setDefaultHeaders(clientHeaders)
            .setRequestConfigCallback(c -> {
                c.setConnectTimeout(Math.toIntExact(remoteInfo.getConnectTimeout().millis()));
                c.setSocketTimeout(Math.toIntExact(remoteInfo.getSocketTimeout().millis()));
                return c;
            })
            .setHttpClientConfigCallback(c -> {
                // Enable basic auth if it is configured
                if (remoteInfo.getUsername() != null) {
                    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(remoteInfo.getUsername(),
                            remoteInfo.getPassword());
                    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                    credentialsProvider.setCredentials(AuthScope.ANY, creds);
                    c.setDefaultCredentialsProvider(credentialsProvider);
                }
                // Stick the task id in the thread name so we can track down tasks from stack traces
                AtomicInteger threads = new AtomicInteger();
                c.setThreadFactory(r -> {
                    String name = "es-client-" + taskId + "-" + threads.getAndIncrement();
                    Thread t = new Thread(r, name);
                    threadCollector.add(t);
                    return t;
                });
                // Limit ourselves to one reactor thread because for now the search process is single threaded.
                c.setDefaultIOReactorConfig(IOReactorConfig.custom().setIoThreadCount(1).build());
                return c;
            }).build();
}
项目:elasticsearch_my    文件:RestClientBenchmark.java   
@Override
protected RestClient client(String benchmarkTargetHost) {
    return RestClient
        .builder(new HttpHost(benchmarkTargetHost, 9200))
        .setHttpClientConfigCallback(b -> b.setDefaultHeaders(
            Collections.singleton(new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "gzip"))))
        .setRequestConfigCallback(b -> b.setContentCompressionEnabled(true))
        .build();
}
项目:minlia-iot    文件:JsonApiHttpExecutor.java   
@Override
public List<Header> customHeader() {
  List<Header> headers= Lists.newArrayList();
  headers.add(new BasicHeader(HEADER_ACCEPT_PARAMETER, APPLICATION_JSON_VALUE_WITH_ENCODING));
  headers.add(new BasicHeader(HEADER_CONTENT_TYPE_PARAMETER, APPLICATION_JSON_VALUE_WITH_ENCODING));
  return headers;
}
项目:elasticsearch_my    文件:ResponseHeaderPluginIT.java   
public void testThatSettingHeadersWorks() throws IOException {
    ensureGreen();
    try {
        getRestClient().performRequest("GET", "/_protected");
        fail("request should have failed");
    } catch(ResponseException e) {
        Response response = e.getResponse();
        assertThat(response.getStatusLine().getStatusCode(), equalTo(401));
        assertThat(response.getHeader("Secret"), equalTo("required"));
    }

    Response authResponse = getRestClient().performRequest("GET", "/_protected", new BasicHeader("Secret", "password"));
    assertThat(authResponse.getStatusLine().getStatusCode(), equalTo(200));
    assertThat(authResponse.getHeader("Secret"), equalTo("granted"));
}
项目:boohee_v5.6    文件:HurlStack.java   
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap();
    map.putAll(request.getHeaders());
    map.putAll(additionalHeaders);
    if (this.mUrlRewriter != null) {
        String rewritten = this.mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    HttpURLConnection connection = openConnection(new URL(url), request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, (String) map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    if (connection.getResponseCode() == -1) {
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) {
        response.setEntity(entityFromConnection(connection));
    }
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            response.addHeader(new BasicHeader((String) header.getKey(), (String) ((List) header.getValue()).get(0)));
        }
    }
    return response;
}
项目:elasticsearch_my    文件:ContextAndHeaderTransportIT.java   
public void testThatRelevantHttpHeadersBecomeRequestHeaders() throws IOException {
    final String IRRELEVANT_HEADER = "SomeIrrelevantHeader";
    Response response = getRestClient().performRequest("GET", "/" + queryIndex + "/_search",
            new BasicHeader(CUSTOM_HEADER, randomHeaderValue), new BasicHeader(IRRELEVANT_HEADER, randomHeaderValue));
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    List<RequestAndHeaders> searchRequests = getRequests(SearchRequest.class);
    assertThat(searchRequests, hasSize(greaterThan(0)));
    for (RequestAndHeaders requestAndHeaders : searchRequests) {
        assertThat(requestAndHeaders.headers.containsKey(CUSTOM_HEADER), is(true));
        // was not specified, thus is not included
        assertThat(requestAndHeaders.headers.containsKey(IRRELEVANT_HEADER), is(false));
    }
}
项目:elasticsearch_my    文件:CorsRegexIT.java   
public void testThatRegularExpressionReturnsForbiddenOnNonMatch() throws IOException {
    try {
        getRestClient().performRequest("GET", "/", new BasicHeader("User-Agent", "Mozilla Bar"),
                new BasicHeader("Origin", "http://evil-host:9200"));
        fail("request should have failed");
    } catch(ResponseException e) {
        Response response = e.getResponse();
        // a rejected origin gets a FORBIDDEN - 403
        assertThat(response.getStatusLine().getStatusCode(), is(403));
        assertThat(response.getHeader("Access-Control-Allow-Origin"), nullValue());
    }
}
项目:Tenable.io-SDK-for-Java    文件:DockerImageHelper.java   
private String uploadManifest( String token, String name, String tag, int configSize, String configDigest, int dataSize, String digestTgz ) throws TenableIoException {
    List<Header> headers = new ArrayList( 2 );
    headers.add( getTokenHeader( token ) );
    headers.add( new BasicHeader( "Content-Type", "application/vnd.docker.distribution.manifest.v2+json" ) );

    ObjectMapper mapper = new ObjectMapper();

    ObjectNode configNode = mapper.createObjectNode();
    configNode.put( "mediaType", "application/vnd.docker.container.image.v1+json" );
    configNode.put( "size", configSize );
    configNode.put( "digest", configDigest );

    ObjectNode layerNode = mapper.createObjectNode();
    layerNode.put( "mediaType", "application/vnd.docker.image.rootfs.diff.tar.gzip" );
    layerNode.put( "size", dataSize );
    layerNode.put( "digest", digestTgz );

    ObjectNode manifest = mapper.createObjectNode();
    manifest.put( "schemaVersion", 2 );
    manifest.put( "mediaType", "application/vnd.docker.distribution.manifest.v2+json" );
    manifest.set( "config", configNode );
    manifest.set( "layers", mapper.createArrayNode().add( layerNode ) );

    try {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode manifestJson = objectMapper.readTree( manifest.toString() );

        StringBuilder hostUrlParams = new StringBuilder();
        hostUrlParams.append( "/v2/" ).append( name ).append( "/manifests/" ).append( tag );

        AsyncHttpService asyncHttpService = new AsyncHttpService( headers );
        HttpFuture httpFuture = asyncHttpService.doPut( getHostUrl( hostUrlParams.toString() ).build(), manifestJson );

        return httpFuture.getResponseHeaders( "Docker-Content-Digest" )[0].getValue();
    } catch ( Exception e ) {
        throw new TenableIoException( TenableIoErrorCode.Generic, "Error while uploading manifest.", e );
    }
}
项目:elasticsearch_my    文件:CorsRegexIT.java   
public void testThatPreFlightRequestReturnsNullOnNonMatch() throws IOException {
    try {
        getRestClient().performRequest("OPTIONS", "/", new BasicHeader("User-Agent", "Mozilla Bar"),
                new BasicHeader("Origin", "http://evil-host:9200"),
                new BasicHeader("Access-Control-Request-Method", "GET"));
        fail("request should have failed");
    } catch(ResponseException e) {
        Response response = e.getResponse();
        // a rejected origin gets a FORBIDDEN - 403
        assertThat(response.getStatusLine().getStatusCode(), is(403));
        assertThat(response.getHeader("Access-Control-Allow-Origin"), nullValue());
        assertThat(response.getHeader("Access-Control-Allow-Methods"), nullValue());
    }
}
项目:degiro-java-client    文件:DeGiroImpl.java   
private void requestPriceUpdate() throws DeGiroException, IOException {
    ensureVwdSession();
    List<Header> headers = new ArrayList<>(1);
    headers.add(new BasicHeader("Origin", session.getConfig().getTradingUrl()));

    HashMap<String, String> data = new HashMap();
    data.put("controlData", generatePriceRequestPayload());

    DResponse response = comm.getUrlData("https://degiro.quotecast.vwdservices.com/CORS", "/" + session.getVwdSession(), data, headers);
    getResponseData(response);
    session.setLastVwdSessionUsed(System.currentTimeMillis());

}
项目:aws-request-signing-apache-interceptor    文件:AWSRequestSigningApacheInterceptor.java   
/**
 * @param mapHeaders Map of header entries
 * @return modeled Header objects
 */
private static Header[] mapToHeaderArray(final Map<String, String> mapHeaders) {
    Header[] headers = new Header[mapHeaders.size()];
    int i = 0;
    for (Map.Entry<String, String> headerEntry : mapHeaders.entrySet()) {
        headers[i++] = new BasicHeader(headerEntry.getKey(), headerEntry.getValue());
    }
    return headers;
}
项目:minlia-iot    文件:FormDataWithJsonApiHttpExecutor.java   
@Override
public List<Header> customHeader() {
    List<Header> headers= Lists.newArrayList();
    headers.add(new BasicHeader(HEADER_ACCEPT_PARAMETER,HEADER_ACCEPT_ALL_ACCEPTED_VALUE));
    headers.add(new BasicHeader(HEADER_CONTENT_TYPE_PARAMETER, APPLICATION_FORM_DATA_VALUE_WITH_ENCODING));
    return headers;
}
项目:BUbiNG    文件:RandomTestMocks.java   
public HttpResponse(final int maxNumberOfHeaders, final int maxLenghtOfHeader, final int maxLengthOfBody, final int pos) {
    this.statusLine = new BasicStatusLine(PROTOCOL_VERSION, 200, "OK");
    Header[] headers = randomHeaders(maxNumberOfHeaders, maxLenghtOfHeader);
    headers[RNG.nextInt(headers.length)] = new BasicHeader("Position", Integer.toString(pos));
    this.setHeaders(headers);
    this.content = RandomStringUtils.randomAscii(RNG.nextInt(maxLengthOfBody) + 1);
    byte[] body = Util.toByteArray(content);
    this.addHeader("Content-Length", Integer.toString(body.length));
    this.entity = new ByteArrayEntity(body, ContentType.DEFAULT_BINARY);
}
项目:Snow-Globe    文件:ResponseVerificationTest.java   
@Test
public void shouldVerifyResponseHeader() {
    String responseHeader = "headerKey";
    Header header = new BasicHeader(responseHeader, "someValue");
    when(response.getAllHeaders()).thenReturn(new Header[]{header});

    buildVerification().expectResponseHeader(responseHeader);
    buildVerification().andExpectResponseHeader(responseHeader);
}
项目:Snow-Globe    文件:ResponseVerificationTest.java   
@Test
public void shouldVerifyResponseHeaderMatchesRegex() {
    String key = "key";
    String value = valueOf(System.currentTimeMillis());
    Header header = new BasicHeader(key, value);
    Header[] allHeaders  = {header};
    when(response.getAllHeaders()).thenReturn(allHeaders);

    buildVerification().andExpectResponseHeaderMatches(key, "[0-9]+");
}
项目:Tenable.io-SDK-for-Java    文件:DockerImageHelper.java   
private TokenData getAuthorizationToken() throws TenableIoException {
    List<Header> headers = new ArrayList( 1 );
    String base64Params = Base64.encodeBase64String( ( ApiParametersHelper.getAccessKey() + ":" + ApiParametersHelper.getSecretKey() ).getBytes() ).toString();

    headers.add( new BasicHeader( "Authorization", "Basic " + base64Params ) );

    AsyncHttpService asyncHttpService = new AsyncHttpService( headers );
    HttpFuture httpFuture = asyncHttpService.doGet( getHostUrl( "/v2/token" ).addParameter( "service", "tenable.io" ).build() );
    TokenData tokenData = httpFuture.getAsType( new TypeReference<TokenData>() {} );

    return tokenData;
}