Java Code Examples for org.apache.http.client.methods.HttpRequestBase#addHeader()

The following examples show how to use org.apache.http.client.methods.HttpRequestBase#addHeader() . 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: ApiClient.java    From amex-api-java-client-core with Apache License 2.0 5 votes vote down vote up
private ApiClientResponse execute(HttpHost httpHost, ApiClientRequest request, AuthProvider authProvider) {
    try {

        if (httpClient == null) {
            httpClient = createClient();
        }
        HttpRequestBase httpRequest = getHttpRequest(httpHost, request, authProvider);

        if (tokenRequesterId != null && !"".equalsIgnoreCase(tokenRequesterId)) {
            httpRequest.addHeader(AuthHeaderNames.X_AMEX_TOKENREQUESTER_ID, tokenRequesterId);
        }

        HttpResponse response = httpClient.execute(httpHost, httpRequest);

        if (response != null && response.getStatusLine().getStatusCode() != 200) {
            throw new ExecutorException("Received http status from server: " +
                    response.getStatusLine().getStatusCode());
        }

        if (response == null) {
            return new ApiClientResponse(null, null);

        } else {
            return new ApiClientResponse(response.getAllHeaders(), EntityUtils.toString(response.getEntity()));

        }

    } catch (Exception e) {
        throw new ExecutorException("Exception sending request to server: " + e.getMessage(), e);
    }
}
 
Example 2
Source File: ConfluenceRestClient.java    From confluence-publisher with Apache License 2.0 5 votes vote down vote up
<T> T sendRequest(HttpRequestBase httpRequest, Function<HttpResponse, T> responseHandler) {
    httpRequest.addHeader(AUTHORIZATION, basicAuthorizationHeaderValue(this.username, this.password));

    try (CloseableHttpResponse response = this.httpClient.execute(httpRequest)) {
        return responseHandler.apply(response);
    } catch (IOException e) {
        throw new RequestFailedException(httpRequest, null, e);
    }
}
 
Example 3
Source File: GenericCommand.java    From data-prep with Apache License 2.0 5 votes vote down vote up
private void addAuthorizationHeaders(HttpRequestBase request) {
    if (StringUtils.isNotBlank(getAuthenticationToken())) {
        request.addHeader(HttpHeaders.AUTHORIZATION, getAuthenticationToken());
    } else {
        // Intentionally left as debug to prevent log flood in open source edition.
        LOGGER.debug("No current authentication token for {}.", this.getClass());
    }
}
 
Example 4
Source File: SyndesisHttpClient.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private static void addDefaultHeaders(HttpRequestBase request) {
    request.addHeader("Accept", "application/json");
    request.addHeader("X-Forwarded-User", "user");
    request.addHeader("SYNDESIS-XSRF-TOKEN", "awesome");
    request.addHeader("X-Forwarded-Access-Token", "supersecret");
    request.addHeader("Content-Type", "application/json");
}
 
Example 5
Source File: ServletTestCaseRequest.java    From Benchmark with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
void buildCookies(HttpRequestBase request) {
	for (Node cookie : getCookies()) {
		String name = XMLCrawler.getAttributeValue("name", cookie);
		String value = XMLCrawler.getAttributeValue("value", cookie);
		request.addHeader("Cookie", name + "=" + URLEncoder.encode(value));
	}
}
 
Example 6
Source File: ConnectorCommon.java    From nextcloud-java-api with GNU General Public License v3.0 5 votes vote down vote up
private <R> CompletableFuture<R> executeRequest(final ResponseParser<R> parser, HttpRequestBase request)
        throws IOException, ClientProtocolException
{
    // https://docs.nextcloud.com/server/14/developer_manual/core/ocs-share-api.html
    request.addHeader("OCS-APIRequest", "true");
    request.addHeader("Content-Type", "application/x-www-form-urlencoded");
    request.setProtocolVersion(HttpVersion.HTTP_1_1);

    HttpClientContext context = prepareContext();

    CompletableFuture<R> futureResponse = new CompletableFuture<>();
    HttpAsyncClientSingleton.getInstance(serverConfig).execute(request, context, new ResponseCallback<>(parser, futureResponse));
    return futureResponse;
}
 
Example 7
Source File: HttpRestHelper.java    From devicehive-java-server with Apache License 2.0 5 votes vote down vote up
private void addHeaders(HttpRequestBase httpRequest, String token) {
    httpRequest.addHeader("Content-Type", MediaType.APPLICATION_JSON);
    if (!StringUtils.isEmpty(token)) {
        String authorization = token.startsWith(TOKEN_PREFIX) ? token : TOKEN_PREFIX + token;
        httpRequest.addHeader(AUTHORIZATION, authorization);
    }
}
 
Example 8
Source File: UrkundAPIUtil.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
private static void addAuthorization(HttpRequestBase request, String user, String pwd) {
	try {
		//String authHeaderStr = String.format("Basic %s", new String(Base64.encodeBase64(String.format("%s:%s", user, pwd).getBytes()), "UTF-8"));
		String authHeaderStr = String.format("Basic %s", new String(Base64.getEncoder().encode(String.format("%s:%s", user, pwd).getBytes("UTF-8"))));
		request.addHeader("Authorization", authHeaderStr);
	} catch(Exception e){
		log.error("ERROR adding authorization header : ", e);
	}
}
 
Example 9
Source File: RestApiConnector.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
protected void addHeaders(HttpRequestBase httpRequest) {
  if (this.accessToken != null) {
    httpRequest.addHeader("Authorization", "OAuth " + this.accessToken);
  }
  httpRequest.addHeader("Content-Type", "application/json");
  //httpRequest.addHeader("Accept-Encoding", "zip");
  //httpRequest.addHeader("Content-Encoding", "gzip");
  //httpRequest.addHeader("Connection", "Keep-Alive");
  //httpRequest.addHeader("Keep-Alive", "timeout=60000");
}
 
Example 10
Source File: StreamsRestUtils.java    From streamsx.topology with Apache License 2.0 5 votes vote down vote up
/**
 * Gets a JSON response to an HTTP call
 * 
 * @param httpClient HTTP client to use for call
 * @param auth Authentication header contents, or null
 * @param inputString REST call to make
 * @return response from the inputString
 * @throws IOException
 */
static JsonObject getGsonResponse(CloseableHttpClient httpClient,
        HttpRequestBase request) throws IOException {
    request.addHeader("accept",
            ContentType.APPLICATION_JSON.getMimeType());

    try (CloseableHttpResponse response = httpClient.execute(request)) {
        return gsonFromResponse(response);
    }
}
 
Example 11
Source File: KylinClient.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
private void addHttpHeaders(HttpRequestBase method) {
    method.addHeader("Accept", "application/json, text/plain, */*");
    method.addHeader("Content-Type", "application/json");
    method.addHeader("User-Agent", "KylinJDBCDriver");

    String username = connProps.getProperty("user");
    String password = connProps.getProperty("password");
    String basicAuth = DatatypeConverter
            .printBase64Binary((username + ":" + password).getBytes(StandardCharsets.UTF_8));
    method.addHeader("Authorization", "Basic " + basicAuth);
}
 
Example 12
Source File: RestClient.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
private void addHttpHeaders(HttpRequestBase method) {
    method.addHeader("Accept", "application/json, text/plain, */*");
    method.addHeader("Content-Type", APPLICATION_JSON);
    String basicAuth = DatatypeConverter
            .printBase64Binary((this.userName + ":" + this.password).getBytes(StandardCharsets.UTF_8));
    method.addHeader("Authorization", "Basic " + basicAuth);
}
 
Example 13
Source File: InvalidHtpRequestTestCase.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultipleTransferEncoding() throws IOException {
    final TestHttpClient client = new TestHttpClient();
    try {
        HttpRequestBase method = new HttpGet(DefaultServer.getDefaultServerURL());
        method.addHeader(HttpHeaderNames.TRANSFER_ENCODING, "chunked");
        method.addHeader(HttpHeaderNames.TRANSFER_ENCODING, "gzip, chunked");
        HttpResponse result = client.execute(method);
        Assert.assertEquals(StatusCodes.BAD_REQUEST, result.getStatusLine().getStatusCode());
    } finally {
        client.getConnectionManager().shutdown();
    }
}
 
Example 14
Source File: RestClient.java    From kylin with Apache License 2.0 5 votes vote down vote up
private void addHttpHeaders(HttpRequestBase method) {
    method.addHeader("Accept", "application/json, text/plain, */*");
    method.addHeader("Content-Type", APPLICATION_JSON);
    if (!Strings.isNullOrEmpty(this.userName) && !Strings.isNullOrEmpty(this.password)) {
        String basicAuth = DatatypeConverter
                .printBase64Binary((this.userName + ":" + this.password).getBytes(StandardCharsets.UTF_8));
        method.addHeader("Authorization", "Basic " + basicAuth);
    }
}
 
Example 15
Source File: AbstractRefTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
protected HttpResponse callUri(
    final ODataHttpMethod httpMethod, final String uri,
    final String additionalHeader, final String additionalHeaderValue,
    final String requestBody, final String requestContentType,
    final HttpStatusCodes expectedStatusCode) throws Exception {

  HttpRequestBase request =
      httpMethod == ODataHttpMethod.GET ? new HttpGet() :
          httpMethod == ODataHttpMethod.DELETE ? new HttpDelete() :
              httpMethod == ODataHttpMethod.POST ? new HttpPost() :
                  httpMethod == ODataHttpMethod.PUT ? new HttpPut() : new HttpPatch();
  request.setURI(URI.create(getEndpoint() + uri));
  if (additionalHeader != null) {
    request.addHeader(additionalHeader, additionalHeaderValue);
  }
  if (requestBody != null) {
    ((HttpEntityEnclosingRequest) request).setEntity(new StringEntity(requestBody));
    request.setHeader(HttpHeaders.CONTENT_TYPE, requestContentType);
  }

  final HttpResponse response = getHttpClient().execute(request);

  assertNotNull(response);
  assertEquals(expectedStatusCode.getStatusCode(), response.getStatusLine().getStatusCode());

  if (expectedStatusCode == HttpStatusCodes.OK) {
    assertNotNull(response.getEntity());
    assertNotNull(response.getEntity().getContent());
  } else if (expectedStatusCode == HttpStatusCodes.CREATED) {
    assertNotNull(response.getEntity());
    assertNotNull(response.getEntity().getContent());
    assertNotNull(response.getFirstHeader(HttpHeaders.LOCATION));
  } else if (expectedStatusCode == HttpStatusCodes.NO_CONTENT) {
    assertTrue(response.getEntity() == null || response.getEntity().getContent() == null);
  }

  return response;
}
 
Example 16
Source File: SelfSignUpUtil.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * This method is used to set the Authorization header for the request sent to consent management service
 *
 * @param httpMethod   The method which requires to add the Authorization header
 * @param tenantDomain The tenant domain
 * @throws APIManagementException APIManagement Exception
 */
private static void setAuthorizationHeader(HttpRequestBase httpMethod, String tenantDomain)
        throws APIManagementException {
    UserRegistrationConfigDTO signupConfig = SelfSignUpUtil.getSignupConfiguration(tenantDomain);
    String adminUsername = signupConfig.getAdminUserName();
    String adminPassword = signupConfig.getAdminPassword();
    String toEncode = adminUsername + ":" + adminPassword;
    byte[] encoding = Base64.encodeBase64(toEncode.getBytes());
    String authHeader = new String(encoding, Charset.defaultCharset());
    httpMethod.addHeader(HTTPConstants.HEADER_AUTHORIZATION,
            APIConstants.AUTHORIZATION_HEADER_BASIC + " " + authHeader);
}
 
Example 17
Source File: AnnotatedServiceTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Test
void testRequestHeaderInjection() throws Exception {
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        HttpRequestBase request = get("/11/aHeader");
        request.setHeader(org.apache.http.HttpHeaders.IF_MATCH, "737060cd8c284d8af7ad3082f209582d");
        testBody(hc, request, "matched");

        request = post("/11/customHeader1");
        request.setHeader("a-name", "minwoox");
        testBody(hc, request, "minwoox is awesome");

        for (int i = 1; i < 4; i++) {
            request = post("/11/customHeader" + i);
            request.addHeader("a-name", "minwoox");
            request.addHeader("a-name", "giraffe");
            testBody(hc, request, "minwoox:giraffe is awesome");
        }

        request = post("/11/customHeader4");
        request.addHeader("a-name", "minwoox");
        request.addHeader("a-name", "giraffe");
        testBody(hc, request, "giraffe:minwoox is awesome");

        request = post("/11/customHeader5");
        request.addHeader("numbers", "1");
        request.addHeader("numbers", "2");
        request.addHeader("numbers", "1");
        request.addHeader("strings", "minwoox");
        request.addHeader("strings", "giraffe");
        request.addHeader("strings", "minwoox");
        testBody(hc, request, "1:2:1/minwoox:giraffe");

        request = get("/11/headerDefault");
        testBody(hc, request, "hello/world/(null)");

        request = get("/11/headerDefault");
        request.setHeader("extra", "people");
        request.setHeader("number", "1");
        testBody(hc, request, "hello/world/people/1");

        request = get("/11/headerWithParam?extra=people&number=2");
        request.setHeader("username", "trustin");
        request.setHeader("password", "hyangtack");
        testBody(hc, request, "trustin/hyangtack/people/2");

        testStatusCode(hc, get("/11/headerWithoutValue"), 400);
    }
}
 
Example 18
Source File: HttpClientUtil.java    From DevToolBox with GNU Lesser General Public License v2.1 4 votes vote down vote up
private static void initHeader(HttpRequestBase base, String header) throws Exception {
    if (header != null && !header.trim().isEmpty()) {
        String[] tmp = header.split("&");
        for (String str : tmp) {
            if (str.startsWith(COOKIE)) {
                base.addHeader(COOKIE, str.replace(COOKIE + "=", ""));
            } else {
                int idx = str.indexOf("=");
                if (idx > 0) {
                    base.addHeader(str.substring(0, idx), str.substring(idx + 1));
                }
            }
        }
    }
    CookieManager cm = (CookieManager) CookieHandler.getDefault();
    Field fd = cm.getClass().getDeclaredField("store");
    fd.setAccessible(true);
    Object cs = fd.get(cm);//cookieStore
    fd = cs.getClass().getDeclaredField("buckets");
    fd.setAccessible(true);
    cs = fd.get(cs);//Map<String,Map<Cookie,Cookie>>
    Method md = cs.getClass().getDeclaredMethod("get", Object.class);
    String domain = base.getURI().getHost();
    Map map = new HashMap();
    while (domain.length() > 0) {
        Object bucket = md.invoke(cs, domain);
        if (bucket != null) {
            map.putAll((Map) bucket);
        }
        int nextPoint = domain.indexOf('.');
        if (nextPoint != -1) {
            domain = domain.substring(nextPoint + 1);
        } else {
            break;
        }
    }
    if (!map.isEmpty()) {
        Iterator it = map.keySet().iterator();
        StringBuilder sb = new StringBuilder();
        while (it.hasNext()) {
            Object next = it.next();
            fd = next.getClass().getDeclaredField("name");
            fd.setAccessible(true);
            sb.append(fd.get(next));
            fd = next.getClass().getDeclaredField("value");
            fd.setAccessible(true);
            sb.append("=").append(fd.get(next)).append(";");
        }
        if (!sb.toString().isEmpty()) {
            Header h = base.getFirstHeader(COOKIE);
            String ck = "";
            if (h != null) {
                ck = h.getValue();
            }
            base.addHeader(COOKIE, sb.toString() + ck);
        }
    }
}
 
Example 19
Source File: TestHttpClient.java    From smartsheet-java-sdk with Apache License 2.0 4 votes vote down vote up
@Override
public HttpRequestBase createApacheRequest(HttpRequest smartsheetRequest) {
    HttpRequestBase apacheHttpRequest = super.createApacheRequest(smartsheetRequest);
    apacheHttpRequest.addHeader("Api-Scenario",apiScenario);
    return apacheHttpRequest;
}
 
Example 20
Source File: BackDoor.java    From teammates with GNU General Public License v2.0 4 votes vote down vote up
private static void addAuthKeys(HttpRequestBase request) {
    request.addHeader("Backdoor-Key", TestProperties.BACKDOOR_KEY);
    request.addHeader("CSRF-Key", TestProperties.CSRF_KEY);
}