List of usage examples for org.apache.http.client.methods HttpRequestBase addHeader
public void addHeader(Header header)
From source file:com.google.dataconnector.client.fetchrequest.HttpFetchStrategy.java
/** * Copies the headers from the inbound request proto to the actual http request. *///from w w w . j av a 2s . c o m void copyHeaders(FetchRequest request, HttpRequestBase httpRequest) throws IOException { for (MessageHeader h : request.getHeadersList()) { if ("x-sdc-agent-cookie".equalsIgnoreCase(h.getKey())) { // set the cookie continue; } Header httpHeader = new BasicHeader(h.getKey(), h.getValue()); LOG.debug(request.getId() + ": Header = " + h.getKey() + ", " + h.getValue()); httpRequest.addHeader(httpHeader); } // Tell the server to close down for keep-alive connections. httpRequest.addHeader(new BasicHeader("Connection", "close")); }
From source file:io.liveoak.keycloak.AuthInterceptorTest.java
private HttpRequestBase createHttpMethod(String method, String uri) { HttpRequestBase httpMethod; switch (method) { case "GET": httpMethod = new HttpGet(uri); break;/*from w w w . j a v a2 s .co m*/ case "POST": httpMethod = new HttpPost(uri); break; case "PUT": httpMethod = new HttpPut(uri); break; case "DELETE": httpMethod = new HttpDelete(uri); break; default: throw new IllegalArgumentException("Unsupported method: " + method); } httpMethod.addHeader(new BasicHeader("Accept", "application/json")); httpMethod.addHeader(new BasicHeader("Content-Type", "application/json")); return httpMethod; }
From source file:io.liveoak.keycloak.AuthInterceptorTest.java
@Test(timeout = 10000) public void authInterceptorTests() throws Exception { // Test #1 - No auth HttpRequestBase httpMethod = createHttpMethod("GET", "http://localhost:8080/testApp/auth-test"); sendRequestAndCheckStatus(httpMethod, HttpStatus.SC_OK); RequestContext context = mock.pollRequest(2, TimeUnit.SECONDS); assertThat(context.securityContext().isAuthenticated()).isFalse(); // Test #2 - Auth System.err.println("******************"); AccessToken token = tokenUtil.createToken(); httpMethod = createHttpMethod("GET", "http://localhost:8080/testApp/auth-test"); httpMethod.addHeader(new BasicHeader("Authorization", "bearer " + tokenUtil.toString(token))); sendRequestAndCheckStatus(httpMethod, HttpStatus.SC_OK); SecurityContext securityContext = mock.pollRequest(10, TimeUnit.SECONDS).securityContext(); assertThat(securityContext.isAuthenticated()).isTrue(); assertThat(securityContext.getRealm()).isEqualTo("liveoak-apps"); assertThat(securityContext.getSubject()).isEqualTo("user-id"); assertThat(securityContext.getUser()).isNotNull(); assertThat(securityContext.getUser().givenName()).isEqualTo("given"); assertThat(securityContext.getUser().familyName()).isEqualTo("family"); assertThat(securityContext.getUser().email()).isEqualTo("email"); assertThat(securityContext.getRoles().size()).isEqualTo(3); assertThat(securityContext.lastVerified()).isEqualTo(token.getIssuedAt()); // Test #3 - Auth expired token = tokenUtil.createToken();/*from w ww. j a v a 2 s . c om*/ token.expiration((int) ((System.currentTimeMillis() / 1000) - 10)); httpMethod = createHttpMethod("GET", "http://localhost:8080/testApp/auth-test"); httpMethod.addHeader(new BasicHeader("Authorization", "bearer " + tokenUtil.toString(token))); sendRequestAndCheckStatus(httpMethod, HttpStatus.SC_UNAUTHORIZED); // Test #4 - Invalid auth httpMethod = createHttpMethod("GET", "http://localhost:8080/testApp/auth-test"); httpMethod.addHeader(new BasicHeader("Authorization", "bearer invalid-token")); sendRequestAndCheckStatus(httpMethod, HttpStatus.SC_UNAUTHORIZED); }
From source file:com.streamreduce.util.HTTPUtils.java
/** * Opens a connection to the specified URL with the supplied username and password, * if supplied, and then reads the contents of the URL. * * @param url the url to open and read from * @param method the method to use for the request * @param data the request body as string * @param mediaType the media type of the request * @param username the username, if any * @param password the password, if any * @param requestHeaders the special request headers to send * @param responseHeaders save response headers * @return the read string from the// w ww. j a va 2s.c om * @throws InvalidCredentialsException if the connection credentials are invalid * @throws IOException if there is a problem with the request */ public static String openUrl(String url, String method, String data, String mediaType, @Nullable String username, @Nullable String password, @Nullable List<Header> requestHeaders, @Nullable List<Header> responseHeaders) throws InvalidCredentialsException, IOException { String response = null; /* Set the cookie policy */ httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); /* Set the user agent */ httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, Constants.NODEABLE_HTTP_USER_AGENT); HttpContext context = new BasicHttpContext(); HttpRequestBase httpMethod; if (method.equals("DELETE")) { httpMethod = new HttpDelete(url); } else if (method.equals("GET")) { httpMethod = new HttpGet(url); } else if (method.equals("POST")) { httpMethod = new HttpPost(url); } else if (method.equals("PUT")) { httpMethod = new HttpPut(url); } else { throw new IllegalArgumentException("The method you specified is not supported."); } // Put data into the request for POST and PUT requests if (method.equals("POST") || method.equals("PUT") && data != null) { HttpEntityEnclosingRequestBase eeMethod = (HttpEntityEnclosingRequestBase) httpMethod; eeMethod.setEntity(new StringEntity(data, ContentType.create(mediaType, "UTF-8"))); } /* Set the username/password if any */ if (username != null) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(username, password)); context.setAttribute(ClientContext.CREDS_PROVIDER, credentialsProvider); } /* Add request headers if need be */ if (requestHeaders != null) { for (Header header : requestHeaders) { httpMethod.addHeader(header); } } LOGGER.debug("Making HTTP request as " + (username != null ? username : "anonymous") + ": " + method + " - " + url); /* Make the request and read the response */ try { HttpResponse httpResponse = httpClient.execute(httpMethod); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { response = EntityUtils.toString(entity); } int responseCode = httpResponse.getStatusLine().getStatusCode(); if (responseCode == 401 || responseCode == 403) { throw new InvalidCredentialsException("The connection credentials are invalid."); } else if (responseCode < 200 || responseCode > 299) { throw new IOException( "Unexpected status code of " + responseCode + " for a " + method + " request to " + url); } if (responseHeaders != null) { responseHeaders.addAll(Arrays.asList(httpResponse.getAllHeaders())); } } catch (IOException e) { httpMethod.abort(); throw e; } return response; }
From source file:org.sentilo.common.rest.impl.RESTClientImpl.java
private String executeHttpCall(final HttpRequestBase httpRequest, final String body, final String identityToken) throws RESTClientException { try {/*from ww w. j ava 2 s. c om*/ logger.debug("Executing http call {} ", httpRequest.toString()); if (StringUtils.hasText(body)) { ((HttpEntityEnclosingRequestBase) httpRequest) .setEntity(new StringEntity(body, ContentType.APPLICATION_JSON)); } if (StringUtils.hasText(identityToken)) { httpRequest.addHeader(RESTUtils.buildIdentityHeader(identityToken)); } if (StringUtils.hasText(secretKey)) { addSignedHeader(httpRequest, body); } final HttpResponse response = httpClient.execute(httpRequest); validateResponse(response); return EntityUtils.toString(response.getEntity()); } catch (final RESTClientException e) { throw e; } catch (final Exception e) { final String msg = String.format("Error while executing http call: %s ", httpRequest.toString()); throw new RESTClientException(msg, e); } }
From source file:org.bigmouth.nvwa.network.http.utils.HttpUtils.java
private static HttpResponse access(HttpRequest request) throws UnexpectStatusCodeException, HttpException { String url = request.getUrl(); if (StringUtils.isBlank(url)) throw new IllegalArgumentException("url"); HttpClient http = HttpClientHelper.http(request.getTimeout()); try {//from w ww. j a va2s . c om if (LOGGER.isDebugEnabled()) { LOGGER.debug("-{}", url); } Method method = request.getMethod(); HttpRequestBase requestBase = null; List<NameValuePair> pairs = request.getPairs(); List<Header> headers = request.getHeaders(); if (method == Method.POST) { HttpPost post = HttpClientHelper.post(url); byte[] entity = request.getEntity(); if (!CollectionUtils.isEmpty(pairs)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("?-{}", pairs); } HttpClientHelper.addPair(post, pairs.toArray(new NameValuePair[0])); } if (!ArrayUtils.isEmpty(entity)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("?-{}", entity); } HttpClientHelper.addByteArrayEntity(post, entity); } requestBase = post; } else if (method == Method.GET) { HttpGet get = HttpClientHelper.get(url); if (!CollectionUtils.isEmpty(pairs)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("?-{}", pairs); } HttpClientHelper.addPair(get, pairs.toArray(new NameValuePair[0])); } requestBase = get; } else { throw new IllegalArgumentException("Not supported method type: " + method); } if (!CollectionUtils.isEmpty(headers)) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("-{}", headers); } for (Header header : headers) { requestBase.addHeader(header); } } long start = System.currentTimeMillis(); org.apache.http.HttpResponse httpResponse = http.execute(requestBase); if (LOGGER.isDebugEnabled()) { LOGGER.debug(" {} ", (System.currentTimeMillis() - start)); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != request.getExpectStatusCode()) { if (request.isThrowUnexpectStatusCode()) throw new UnexpectStatusCodeException(statusCode); } String response = HttpClientHelper.getResponseBody(httpResponse, false, request.getCharset()); Header[] allHeaders = httpResponse.getAllHeaders(); HttpResponse hrp = new HttpResponse(); hrp.addAllHeaders(allHeaders); hrp.setEntityString(response); hrp.setStatusCode(statusCode); return hrp; } catch (Exception e) { throw new HttpException(e); } finally { http.getConnectionManager().shutdown(); } }