org.apache.http.message.BasicHeader Java Examples

The following examples show how to use org.apache.http.message.BasicHeader. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AuthHttpClientTestCase.java    From docker-java-api with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Leaves the request's header intact if it exists.
 * @throws Exception If something goes wrong.
 */
@Test
public void leavesExistingHeaderAlone() throws Exception {
    final Header auth = new BasicHeader("X-Registry-Auth", "12356");
    final HttpUriRequest request = new HttpGet();
    request.setHeader(auth);
    new AuthHttpClient(
        noOpClient,
        this.fakeAuth("X-New-Header", "abc")
    ).execute(request);
    MatcherAssert.assertThat(
        request.getFirstHeader("X-Registry-Auth").getValue(),
        new IsEqual<>("12356")
    );
    MatcherAssert.assertThat(
        request.getFirstHeader("X-New-Header").getValue(),
        new IsEqual<>("abc")
    );
}
 
Example #2
Source File: Awvs.java    From TrackRay with GNU General Public License v3.0 6 votes vote down vote up
public void initCheck(){
    headers = new Header[]{
            new BasicHeader("X-Auth",apikey),
            new BasicHeader("content-type","application/json"),
    };

    CrawlerPage page = new CrawlerPage();
    page.getRequest().setUrl(host+"/api/v1/scans");
    page.getRequest().setHttpHeaders(headers);
    page.getRequest().setHttpMethod(HttpMethod.GET);
    f.run(page);
    int statusCode = page.getResponse().getStatus().getStatusCode();
    if (statusCode>=200 && statusCode<300){
        ok = true;
        SysLog.info("[AWVS] AWVS配置正常");
    }else {
        ok = false;
        SysLog.error("[AWVS] AWVS配置异常请检查");
    }

}
 
Example #3
Source File: Wordpress001.java    From TrackRay with GNU General Public License v3.0 6 votes vote down vote up
@Override
public String start() {

    String url = param.get("target")+"/wp-login.php?action=lostpassword";

    crawlerPage.getRequest().setUrl(url);
    crawlerPage.getRequest().setHttpMethod(HttpMethod.POST);
    HashMap<String, String> map = new HashMap<>();
    map.put("user_login",param.get("username").toString());
    map.put("redirect_to","");
    map.put("wp-submit","Get+New+Password");
    crawlerPage.getRequest().addHttpHeader(new BasicHeader("Host",param.get("host").toString()));
    crawlerPage.getRequest().setParamMap(map);
    fetcher.run(crawlerPage);
    return crawlerPage.getResponse().getStatus().getContent();
}
 
Example #4
Source File: Faucet.java    From jlibra with Apache License 2.0 6 votes vote down vote up
public void mint(AuthenticationKey authenticationKey, long amountInMicroLibras, String currencyCode) {
    try {
        URIBuilder builder = new URIBuilder(url)
                .setParameter("amount", Long.toString(amountInMicroLibras))
                .setParameter("auth_key", authenticationKey.toString())
                .setParameter("currency_code", currencyCode);
        HttpPost httpPost = new HttpPost(builder.build().toString());
        httpPost.addHeader(new BasicHeader(USER_AGENT, "JLibra"));
        httpPost.setEntity(new StringEntity(""));

        CloseableHttpResponse response = httpClient.execute(httpPost);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new LibraRuntimeException(String.format("Mint failed. Status code: %d, message: %s",
                    response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()));
        }
    } catch (IOException | URISyntaxException e) {
        throw new LibraRuntimeException("Mint failed", e);
    }
}
 
Example #5
Source File: HttpUtil.java    From ObjectLogger with Apache License 2.0 6 votes vote down vote up
private synchronized String sendPost(String url, List<NameValuePair> nameValuePairList) throws Exception {
    CloseableHttpResponse response = null;
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        HttpPost post = new HttpPost(url);
        StringEntity entity = new UrlEncodedFormEntity(nameValuePairList, "UTF-8");
        post.setEntity(entity);
        post.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));
        post.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));
        response = client.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();
        if (200 == statusCode) {
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        }
    } catch (Exception e) {
        LOGGER.error("send post error", e);
    } finally {
        if (response != null) {
            response.close();
        }
    }
    return null;
}
 
Example #6
Source File: TestPasswordAuthentication.java    From presto with Apache License 2.0 6 votes vote down vote up
@Test
public void test()
        throws IOException
{
    String json = new ObjectMapper().writeValueAsString(ImmutableMap.<String, Object>builder()
            .put("value", 42L)
            .build());

    client.getLowLevelClient()
            .performRequest(
                    "POST",
                    "/test/_doc?refresh",
                    ImmutableMap.of(),
                    new NStringEntity(json, ContentType.APPLICATION_JSON),
                    new BasicHeader("Authorization", format("Basic %s", Base64.encodeAsString(format("%s:%s", USER, PASSWORD).getBytes(StandardCharsets.UTF_8)))));

    assertThat(assertions.query("SELECT * FROM test"))
            .matches("VALUES BIGINT '42'");
}
 
Example #7
Source File: HttpUtil.java    From roncoo-education with MIT License 6 votes vote down vote up
/**
 * 
 * @param url
 * @param param
 * @return
 */
public static String post(String url, Map<String, Object> param) {
	logger.info("POST 请求, url={},map={}", url, param.toString());
	try {
		HttpPost httpPost = new HttpPost(url.trim());
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT).setConnectionRequestTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build();
		httpPost.setConfig(requestConfig);
		httpPost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
		StringEntity se = new StringEntity(param.toString(), CHARSET_UTF_8);
		se.setContentType(CONTENT_TYPE_TEXT_JSON);
		se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
		httpPost.setEntity(se);
		HttpResponse httpResponse = HttpClientBuilder.create().build().execute(httpPost);
		return EntityUtils.toString(httpResponse.getEntity(), CHARSET_UTF_8);
	} catch (Exception e) {
		logger.info("HTTP请求出错", e);
		e.printStackTrace();
	}
	return "";
}
 
Example #8
Source File: RtContainer.java    From docker-java-api with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Exec exec(final JsonObject config) throws IOException {
    final URI uri = new UncheckedUriBuilder(
        this.baseUri.toString() + "/exec")
        .build();
    final HttpPost post = new HttpPost(uri);
    try {
        post.setEntity(new StringEntity(config.toString()));
        post.setHeader(new BasicHeader("Content-Type", "application/json"));
        final JsonObject json = this.client.execute(
            post,
            new ReadJsonObject(
                new MatchStatus(post.getURI(), HttpStatus.SC_CREATED)
            )
        );
        return this.docker.execs().get(json.getString("Id"));
    } finally {
        post.releaseConnection();
    }
}
 
Example #9
Source File: CachingTest.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
@Test
public void testRestCachingWithImpersonation() throws Exception {
    final Settings settings = Settings.builder().putList("opendistro_security.authcz.rest_impersonation_user.dummy", "*").build();
    setup(Settings.EMPTY, new DynamicSecurityConfig(), settings);
    final RestHelper rh = nonSslRestHelper();
    HttpResponse res = rh.executeGetRequest("_opendistro/_security/authinfo?pretty", new BasicHeader("opendistro_security_impersonate_as", "impuser"));
    System.out.println(res.getBody());
    Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode());
    res = rh.executeGetRequest("_opendistro/_security/authinfo?pretty", new BasicHeader("opendistro_security_impersonate_as", "impuser"));
    System.out.println(res.getBody());
    Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode());
    res = rh.executeGetRequest("_opendistro/_security/authinfo?pretty", new BasicHeader("opendistro_security_impersonate_as", "impuser"));
    System.out.println(res.getBody());
    Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode());
    res = rh.executeGetRequest("_opendistro/_security/authinfo?pretty", new BasicHeader("opendistro_security_impersonate_as", "impuser2"));
    System.out.println(res.getBody());
    Assert.assertEquals(HttpStatus.SC_OK, res.getStatusCode());

    Assert.assertEquals(4, DummyHTTPAuthenticator.getCount());
    Assert.assertEquals(3, DummyAuthorizer.getCount());
    Assert.assertEquals(4, DummyAuthenticationBackend.getAuthCount());
    Assert.assertEquals(2, DummyAuthenticationBackend.getExistsCount());

}
 
Example #10
Source File: BasicAuditlogTest.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
@Test
public void testAliasBadHeaders() throws Exception {

    Settings additionalSettings = Settings.builder()
            .put("opendistro_security.audit.type", TestAuditlogImpl.class.getName())
            .put(ConfigConstants.OPENDISTRO_SECURITY_AUDIT_ENABLE_TRANSPORT, true)
            .put(ConfigConstants.OPENDISTRO_SECURITY_AUDIT_RESOLVE_BULK_REQUESTS, true)
            .put(ConfigConstants.OPENDISTRO_SECURITY_AUDIT_CONFIG_DISABLED_TRANSPORT_CATEGORIES, "NONE")
            .put(ConfigConstants.OPENDISTRO_SECURITY_AUDIT_CONFIG_DISABLED_REST_CATEGORIES, "NONE")
            .put("opendistro_security.audit.threadpool.size", 0)
            .build();

    setup(additionalSettings);

    TestAuditlogImpl.clear();
    HttpResponse response = rh.executeGetRequest("_search?pretty", new BasicHeader("_opendistro_security_user", "xxx"), encodeBasicHeader("admin", "admin"));
    Assert.assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode());
    System.out.println(TestAuditlogImpl.sb.toString());
    Assert.assertFalse(TestAuditlogImpl.sb.toString().contains("YWRtaW46YWRtaW4"));
    Assert.assertTrue(TestAuditlogImpl.sb.toString().contains("BAD_HEADERS"));
    Assert.assertTrue(TestAuditlogImpl.sb.toString().contains("xxx"));
    Assert.assertEquals(1, TestAuditlogImpl.messages.size());
    Assert.assertTrue(validateMsgs(TestAuditlogImpl.messages));
    TestAuditlogImpl.clear();
}
 
Example #11
Source File: ApacheHttpClientConfigurationTests.java    From spring-cloud-openfeign with Apache License 2.0 6 votes vote down vote up
@Override
public HttpClientBuilder createBuilder() {
	CloseableHttpClient client = mock(CloseableHttpClient.class);
	CloseableHttpResponse response = mock(CloseableHttpResponse.class);
	StatusLine statusLine = mock(StatusLine.class);
	doReturn(200).when(statusLine).getStatusCode();
	Mockito.doReturn(statusLine).when(response).getStatusLine();
	Header[] headers = new BasicHeader[0];
	doReturn(headers).when(response).getAllHeaders();
	try {
		Mockito.doReturn(response).when(client)
				.execute(any(HttpUriRequest.class));
	}
	catch (IOException e) {
		e.printStackTrace();
	}
	HttpClientBuilder builder = mock(HttpClientBuilder.class);
	Mockito.doReturn(client).when(builder).build();
	return builder;
}
 
Example #12
Source File: HopServer.java    From hop with Apache License 2.0 6 votes vote down vote up
HttpPost buildSendXmlMethod( byte[] content, String service ) throws Exception {
  // Prepare HTTP put
  //
  String urlString = constructUrl( service );
  if ( log.isDebug() ) {
    log.logDebug( BaseMessages.getString( PKG, "HopServer.DEBUG_ConnectingTo", urlString ) );
  }
  HttpPost postMethod = new HttpPost( urlString );

  // Request content will be retrieved directly from the input stream
  //
  HttpEntity entity = new ByteArrayEntity( content );

  postMethod.setEntity( entity );
  postMethod.addHeader( new BasicHeader( "Content-Type", "text/xml;charset=" + Const.XML_ENCODING ) );

  return postMethod;
}
 
Example #13
Source File: HopServer.java    From hop with Apache License 2.0 6 votes vote down vote up
HttpPost buildSendExportMethod( String type, String load, InputStream is ) throws UnsupportedEncodingException {
  String serviceUrl = RegisterPackageServlet.CONTEXT_PATH;
  if ( type != null && load != null ) {
    serviceUrl +=
      "/?" + RegisterPackageServlet.PARAMETER_TYPE + "=" + type
        + "&" + RegisterPackageServlet.PARAMETER_LOAD + "=" + URLEncoder.encode( load, "UTF-8" );
  }

  String urlString = constructUrl( serviceUrl );
  if ( log.isDebug() ) {
    log.logDebug( BaseMessages.getString( PKG, "HopServer.DEBUG_ConnectingTo", urlString ) );
  }

  HttpPost method = new HttpPost( urlString );
  method.setEntity( new InputStreamEntity( is ) );
  method.addHeader( new BasicHeader( "Content-Type", "binary/zip" ) );

  return method;
}
 
Example #14
Source File: MultitenancyTests.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
@Test
public void testMt() throws Exception {
    final Settings settings = Settings.builder()
            .build();
    setup(settings);
    final RestHelper rh = nonSslRestHelper();

    HttpResponse res;
    String body = "{\"buildNum\": 15460, \"defaultIndex\": \"humanresources\", \"tenant\": \"human_resources\"}";
    Assert.assertEquals(HttpStatus.SC_FORBIDDEN, (res = rh.executePutRequest(".kibana/config/5.6.0?pretty",body, new BasicHeader("securitytenant", "blafasel"), encodeBasicHeader("hr_employee", "hr_employee"))).getStatusCode());

    body = "{\"buildNum\": 15460, \"defaultIndex\": \"humanresources\", \"tenant\": \"human_resources\"}";
    Assert.assertEquals(HttpStatus.SC_FORBIDDEN, (res = rh.executePutRequest(".kibana/config/5.6.0?pretty",body, new BasicHeader("securitytenant", "business_intelligence"), encodeBasicHeader("hr_employee", "hr_employee"))).getStatusCode());

    body = "{\"buildNum\": 15460, \"defaultIndex\": \"humanresources\", \"tenant\": \"human_resources\"}";
    Assert.assertEquals(HttpStatus.SC_CREATED, (res = rh.executePutRequest(".kibana/config/5.6.0?pretty",body, new BasicHeader("securitytenant", "human_resources"), encodeBasicHeader("hr_employee", "hr_employee"))).getStatusCode());
    System.out.println(res.getBody());
    Assert.assertTrue(WildcardMatcher.match("*.kibana_*_humanresources*", res.getBody()));

    Assert.assertEquals(HttpStatus.SC_OK, (res = rh.executeGetRequest(".kibana/config/5.6.0?pretty",new BasicHeader("securitytenant", "human_resources"), encodeBasicHeader("hr_employee", "hr_employee"))).getStatusCode());
    System.out.println(res.getBody());
    Assert.assertTrue(WildcardMatcher.match("*human_resources*", res.getBody()));

}
 
Example #15
Source File: LdapBackendIntegTest.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
@Test
public void testAttributesWithImpersonation() throws Exception {
    String securityConfigAsYamlString = FileHelper.loadFile("ldap/config.yml");
    securityConfigAsYamlString = securityConfigAsYamlString.replace("${ldapsPort}", String.valueOf(ldapsPort));
    final Settings settings = Settings.builder()
            .putList(ConfigConstants.OPENDISTRO_SECURITY_AUTHCZ_REST_IMPERSONATION_USERS+".cn=Captain Spock,ou=people,o=TEST", "*")
            .build();
    setup(Settings.EMPTY, new DynamicSecurityConfig().setConfigAsYamlString(securityConfigAsYamlString), settings);
    final RestHelper rh = nonSslRestHelper();
    HttpResponse res;
    Assert.assertEquals(HttpStatus.SC_OK, (res=rh.executeGetRequest("_opendistro/_security/authinfo", new BasicHeader("opendistro_security_impersonate_as", "jacksonm")
            ,encodeBasicHeader("spock", "spocksecret"))).getStatusCode());
    System.out.println(res.getBody());
    Assert.assertTrue(res.getBody().contains("ldap.dn"));
    Assert.assertTrue(res.getBody().contains("attr.ldap.entryDN"));
    Assert.assertTrue(res.getBody().contains("attr.ldap.subschemaSubentry"));

}
 
Example #16
Source File: LdapBackendIntegTest2.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
@Test
public void testAttributesWithImpersonation() throws Exception {
    String securityConfigAsYamlString = FileHelper.loadFile("ldap/config_ldap2.yml");
    securityConfigAsYamlString = securityConfigAsYamlString.replace("${ldapsPort}", String.valueOf(ldapsPort));
    final Settings settings = Settings.builder()
            .putList(ConfigConstants.OPENDISTRO_SECURITY_AUTHCZ_REST_IMPERSONATION_USERS+".cn=Captain Spock,ou=people,o=TEST", "*")
            .build();
    setup(Settings.EMPTY, new DynamicSecurityConfig().setConfigAsYamlString(securityConfigAsYamlString), settings);
    final RestHelper rh = nonSslRestHelper();
    HttpResponse res;
    Assert.assertEquals(HttpStatus.SC_OK, (res=rh.executeGetRequest("_opendistro/_security/authinfo", new BasicHeader("opendistro_security_impersonate_as", "jacksonm")
            ,encodeBasicHeader("spock", "spocksecret"))).getStatusCode());
    System.out.println(res.getBody());
    Assert.assertTrue(res.getBody().contains("ldap.dn"));
    Assert.assertTrue(res.getBody().contains("attr.ldap.entryDN"));
    Assert.assertTrue(res.getBody().contains("attr.ldap.subschemaSubentry"));

}
 
Example #17
Source File: AnomalyDetectorRestTestCase.java    From anomaly-detection with Apache License 2.0 6 votes vote down vote up
protected AnomalyDetector createRandomAnomalyDetector(Boolean refresh, Boolean withMetadata) throws IOException {
    Map<String, Object> uiMetadata = null;
    if (withMetadata) {
        uiMetadata = TestHelpers.randomUiMetadata();
    }
    AnomalyDetector detector = TestHelpers.randomAnomalyDetector(uiMetadata, null);
    String indexName = detector.getIndices().get(0);
    TestHelpers
        .makeRequest(
            client(),
            "POST",
            "/" + indexName + "/_doc/" + randomAlphaOfLength(5) + "?refresh=true",
            ImmutableMap.of(),
            toHttpEntity("{\"name\": \"test\"}"),
            null
        );
    AnomalyDetector createdDetector = createAnomalyDetector(detector, refresh);

    if (withMetadata) {
        return getAnomalyDetector(createdDetector.getDetectorId(), new BasicHeader(HttpHeaders.USER_AGENT, "Kibana"));
    }
    return getAnomalyDetector(createdDetector.getDetectorId(), new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"));
}
 
Example #18
Source File: AcceptanceTestWithTwoServices.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
protected void mockValid200HttpResponseWithAddedCors() throws IOException {
    mockValid200HttpResponseWithHeaders(new Header[]{
        new BasicHeader("Access-Control-Allow-Origin","test"),
        new BasicHeader("Access-Control-Allow-Methods","RANDOM"),
        new BasicHeader("Access-Control-Allow-Headers","origin,x-test"),
        new BasicHeader("Access-Control-Allow-Credentials","true"),
    });
}
 
Example #19
Source File: ElasticsearchMigration.java    From elasticsearch-migration with Apache License 2.0 5 votes vote down vote up
private RestHighLevelClient createElasticsearchClient(ElasticsearchConfig elasticsearchConfig) {
    final RestClientBuilder builder = RestClient.builder(
            elasticsearchConfig.getUrls().stream().map(e -> new HttpHost(e.getHost(), e.getPort(), e.getProtocol())).collect(Collectors.toSet()).toArray(new HttpHost[0])
    );
    builder.setDefaultHeaders(elasticsearchConfig.getHeaders().entries().stream().map(e -> new BasicHeader(e.getKey(), e.getValue())).collect(Collectors.toList()).toArray(new Header[0]));

    if (elasticsearchConfig.getMaxRetryTimeoutMillis() != null) {
        builder.setMaxRetryTimeoutMillis(elasticsearchConfig.getMaxRetryTimeoutMillis());
    }
    if (elasticsearchConfig.getPathPrefix() != null) {
        builder.setPathPrefix(elasticsearchConfig.getPathPrefix());
    }

    return new RestHighLevelClient(builder);
}
 
Example #20
Source File: RequestInterceptorHandler.java    From camunda-external-task-client-java with Apache License 2.0 5 votes vote down vote up
@Override
public void process(HttpRequest httpRequest, HttpContext context) throws HttpException, IOException {
  ClientRequestContextImpl interceptedRequest = new ClientRequestContextImpl();
  interceptors.forEach((ClientRequestInterceptor requestInterceptor) -> {
    try {
      requestInterceptor.intercept(interceptedRequest);
    }
    catch (Throwable e) {
      LOG.requestInterceptorException(e);
    }
  });

  Map<String, String> newHeaders = interceptedRequest.getHeaders();
  newHeaders.forEach((headerName, headerValue) -> httpRequest.addHeader(new BasicHeader(headerName, headerValue)));
}
 
Example #21
Source File: DouYuBroadcastService.java    From Alice-LiveMan with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public String getBroadcastCookies(String username, String password, String captcha) throws Exception {
    Object douyuQRCode = session.getAttribute(SESSION_ATTRIBUTE);
    Map<String, String> requestProperties = new HashMap<>();
    requestProperties.put("referer", "https://passport.douyu.com/index/login?passport_reg_callback=PASSPORT_REG_SUCCESS_CALLBACK&passport_login_callback=PASSPORT_LOGIN_SUCCESS_CALLBACK&passport_close_callback=PASSPORT_CLOSE_CALLBACK&passport_dp_callback=PASSPORT_DP_CALLBACK&type=login&client_id=1&state=https%3A%2F%2Fwww.douyu.com%2F&source=click_topnavi_login");
    requestProperties.put("x-requested-with", "XMLHttpRequest");
    HttpResponse httpResponse = HttpRequestUtil.getHttpResponse(URI.create(String.format(URL_CHECK_CODE, System.currentTimeMillis(), douyuQRCode)), null, requestProperties);
    List<Header> headerList = new ArrayList<>(Arrays.asList(httpResponse.getHeaders("set-cookie")));
    String checkResultJSON = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
    JSONObject checkResult = JSON.parseObject(checkResultJSON);
    if (checkResult.getInteger("error") == 0) {
        URI redirectUrl = URI.create("https:" + checkResult.getJSONObject("data").getString("url"));
        httpResponse = HttpRequestUtil.getHttpResponse(redirectUrl, null, requestProperties);
        String loginResultJSON = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
        JSONObject loginResult = JSON.parseObject(loginResultJSON.substring(1, loginResultJSON.length() - 1));
        if (loginResult.getInteger("error") == 0) {
            headerList.addAll(Arrays.asList(httpResponse.getHeaders("set-cookie")));
            String cookies = headerList.stream().map(header -> header.getValue().split(";")[0]).collect(Collectors.joining(";"));
            httpResponse = HttpRequestUtil.getHttpResponse(URI.create("https://passport.douyu.com/member/login?client_id=97"), cookies, requestProperties);
            String apolloLoginJSON = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
            JSONObject apolloLogin = JSON.parseObject(apolloLoginJSON.substring(1, apolloLoginJSON.length() - 1));
            if (apolloLogin.getInteger("error") == 0) {
                headerList.addAll(Arrays.asList(httpResponse.getHeaders("set-cookie")));
                String randomCtn = SecurityUtils.md5Encode(String.valueOf(System.nanoTime()).getBytes());
                headerList.add(new BasicHeader("set-cookie", "apollo_ctn=" + randomCtn + ";"));
                headerList.add(new BasicHeader("set-cookie", "acf_ccn=" + randomCtn + ";"));
                return headerList.stream().map(header -> header.getValue().split(";")[0]).collect(Collectors.joining(";"));
            } else {
                throw new Exception(loginResult.getString("data"));
            }
        } else {
            throw new Exception(loginResult.getString("data"));
        }
    }
    throw new Exception(checkResult.getString("data"));
}
 
Example #22
Source File: HttpBasicPassTicketScheme.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void applyToRequest(HttpRequest request) {
    request.setHeader(
        new BasicHeader(HttpHeaders.AUTHORIZATION, authorizationValue)
    );
    Header header = request.getFirstHeader(COOKIE_HEADER);
    if (header != null) {
        request.setHeader(COOKIE_HEADER,
            CookieUtil.removeCookie(
                header.getValue(),
                cookieName
            )
        );
    }
}
 
Example #23
Source File: RtContainers.java    From docker-java-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Container create(
    final String name, final JsonObject container
) throws IOException {
    final URI uri;
    if(!name.isEmpty()) {
        uri = new UncheckedUriBuilder(
            this.baseUri.toString().concat("/create")
        ).addParameter("name", name)
            .build();
    } else {
        uri = new UncheckedUriBuilder(
            this.baseUri.toString().concat("/create")
        ).build();
    }
    final HttpPost post = new HttpPost(uri);
    try {
        post.setEntity(new StringEntity(container.toString()));
        post.setHeader(new BasicHeader("Content-Type", "application/json"));
        final JsonObject json = this.client.execute(
            post,
            new ReadJsonObject(
                new MatchStatus(post.getURI(), HttpStatus.SC_CREATED)
            )
        );
        return new RtContainer(
            new Merged(json, container),
            this.client,
            URI.create(
                this.baseUri.toString() + "/" + json.getString("Id")
            ),
            this.docker
        );
    } finally {
        post.releaseConnection();
    }
}
 
Example #24
Source File: CookieManager3Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Test that " are not discarded.
 * Once this test passes, our hack in HttpWebConnection.HtmlUnitBrowserCompatCookieSpec can safely be removed.
 * @see <a href="https://issues.apache.org/jira/browse/HTTPCLIENT-1006">HttpClient bug 1006</a>
 * @throws Exception if the test fails
 */
@Test
public void httpClientParsesCookiesQuotedValuesCorrectly() throws Exception {
    final Header header = new BasicHeader("Set-Cookie", "first=\"hello world\"");
    final DefaultCookieSpec spec = new DefaultCookieSpec();
    final CookieOrigin origin = new CookieOrigin("localhost", 80, "/", false);
    final List<org.apache.http.cookie.Cookie> list = spec.parse(header, origin);
    assertEquals(1, list.size());
    assertEquals("\"hello world\"", list.get(0).getValue());
}
 
Example #25
Source File: RequestUtilsTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
void givenRequestWithHeaders_whenSetNewHeader_thenHeaderCreated() {
    doReturn(new Header[] { contentLenght, pragma}).when(request).getAllHeaders();
    ArgumentCaptor<Header[]> argument = ArgumentCaptor.forClass(Header[].class);

    BasicHeader newHeader = new BasicHeader("fishnets", "mipiace");
    wrapper.setHeader(newHeader);
    verify(request).setHeaders(argument.capture());
    assertThat(argument.getValue(), hasItemInArray(contentLenght));
    assertThat(argument.getValue(), hasItemInArray(pragma));
    assertThat(argument.getValue(), hasItemInArray(newHeader));
}
 
Example #26
Source File: RemoteAxivionDashboard.java    From warnings-ng-plugin with MIT License 5 votes vote down vote up
@Override
public JsonObject getIssues(final AxIssueKind kind) {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, credentials);

    try (CloseableHttpClient client =
                 HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build()) {

        HttpGet httpget = new HttpGet(projectUrl + "/issues?kind=" + kind);
        httpget.addHeader(new BasicHeader("Accept", "application/json"));
        BasicHeader userAgent = new BasicHeader(X_AXIVION_USER_AGENT, API_USER_AGENT);
        httpget.addHeader(userAgent);

        try (CloseableHttpResponse response = client.execute(httpget)) {
            if (response.getStatusLine().getStatusCode() == HTTP_STATUS_OK) {
                return convertToJson(response);
            }
        }

        // dashboard version < 6.9.3 need the fallback header
        httpget.removeHeader(userAgent);
        httpget.addHeader(new BasicHeader(X_AXIVION_USER_AGENT, FALL_USER_AGENT));
        try (CloseableHttpResponse legacyResponse = client.execute(httpget)) {
            return convertToJson(legacyResponse);
        }
    }
    catch (IOException e) {
        throw new ParsingException(e, "Cannot retrieve information from dashboard");
    }
}
 
Example #27
Source File: ESConfiguration.java    From SkaETL with Apache License 2.0 5 votes vote down vote up
@Bean
public RestHighLevelClient elasticsearchRestConnection(ESConfiguration esConfiguration) {
    String auth = esConfiguration.getServiceElasticsearchUsername() + ":" + esConfiguration.getServiceElasticsearchPassword();
    String authB64;
    try {
        authB64 = Base64.getEncoder().encodeToString(auth.getBytes("utf-8"));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("Impossible encoding for user " + esConfiguration.getServiceElasticsearchUsername() + " and password " + esConfiguration.getServiceElasticsearchPassword() + " msg " + e);
    }
    RestClientBuilder builder = RestClient.builder(
            new HttpHost(esConfiguration.getHost(), Integer.valueOf(esConfiguration.getPort()), "http"));
    Header[] defaultHeaders = new Header[]{
            new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"),
            new BasicHeader("cluster.name", esConfiguration.getClusterName()),
            new BasicHeader(HttpHeaders.AUTHORIZATION, "Basic " + authB64)
    };
    builder.setDefaultHeaders(defaultHeaders);
    builder.setMaxRetryTimeoutMillis(esConfiguration.getSocketTimeout() * 1000);
    builder.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
        @Override
        public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) {
            return requestConfigBuilder
                    .setConnectionRequestTimeout(connectionRequestTimeout)
                    .setConnectTimeout(esConfiguration.getConnectionTimeout() * 1000)
                    .setSocketTimeout(esConfiguration.getSocketTimeout() * 1000);
        }
    });
    return new RestHighLevelClient(builder);
}
 
Example #28
Source File: TieBaApi.java    From tieba-api with MIT License 5 votes vote down vote up
/**
 * 文库签到
 * @param bduss bduss
 * @return result
 */
public String wenKuSign(String bduss){
	try {
		HashMap<String, Header> headers = new HashMap<String, Header>();
		headers.put("Host", new BasicHeader("Host", "wenku.baidu.com"));
		headers.put("Referer", new BasicHeader("Referer", "https://wenku.baidu.com/task/browse/daily"));
		HttpResponse response = hk.execute(Constants.WENKU_SIGN_URL, createCookie(bduss), headers);
		String result = EntityUtils.toString(response.getEntity());
		return result;
	} catch (Exception e) {
		logger.error(e.getMessage(), e);
	}
	return null;
}
 
Example #29
Source File: HttpComponentsStreamingClientHttpRequest.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
@Nullable
public Header getContentEncoding() {
	String contentEncoding = this.headers.getFirst("Content-Encoding");
	return (contentEncoding != null ? new BasicHeader("Content-Encoding", contentEncoding) : null);

}
 
Example #30
Source File: ElasticClientManager.java    From elasticsearch-sql with MIT License 5 votes vote down vote up
private RestHighLevelClient initClient(List<HttpHost> httpHosts, boolean useSsl, ClusterMode mode, String token) {
    RestHighLevelClient restHighLevelClient;
    RestClientBuilder restClientBuilder = RestClient.builder(httpHosts.toArray(new HttpHost[0]))
            .setNodeSelector(NodeSelector.SKIP_DEDICATED_MASTERS)
            .setRequestConfigCallback(builder -> builder.setConnectTimeout(50000)
                    .setSocketTimeout(600000));
    if (useSsl) {
        restClientBuilder
                .setHttpClientConfigCallback(httpAsyncClientBuilder -> {
                    httpAsyncClientBuilder.setSSLHostnameVerifier((s, sslSession) -> true);
                    SSLContext sslContext;
                    try {
                        sslContext = SSLContext.getInstance("TLS");
                        sslContext.init(null, TRUST_ALL_CERTS, new java.security.SecureRandom());
                    } catch (NoSuchAlgorithmException | KeyManagementException e) {
                        throw new RuntimeException(e.getMessage());
                    }
                    httpAsyncClientBuilder.setSSLContext(sslContext);
                    String basicToken = Base64.getEncoder().encodeToString(token.getBytes());
                    httpAsyncClientBuilder.setDefaultHeaders(Collections.singletonList(new BasicHeader("Authorization", "Basic " + basicToken)));
                    return httpAsyncClientBuilder;
                });
    }
    if (ClusterMode.CLUSTER.equals(mode)) {
        SniffOnFailureListener sniffOnFailureListener = new SniffOnFailureListener();
        restClientBuilder.setFailureListener(sniffOnFailureListener);
        restHighLevelClient = new RestHighLevelClient(restClientBuilder);
        NodesSniffer nodesSniffer = new ElasticsearchNodesSniffer(restHighLevelClient.getLowLevelClient(),
                ElasticsearchNodesSniffer.DEFAULT_SNIFF_REQUEST_TIMEOUT,
                useSsl ? ElasticsearchNodesSniffer.Scheme.HTTPS : ElasticsearchNodesSniffer.Scheme.HTTP);
        Sniffer sniffer = Sniffer.builder(restHighLevelClient.getLowLevelClient()).setSniffIntervalMillis(5000).setNodesSniffer(nodesSniffer).build();
        sniffOnFailureListener.setSniffer(sniffer);
    } else {
        restHighLevelClient = new RestHighLevelClient(restClientBuilder);
    }
    return restHighLevelClient;
}