Java Code Examples for org.apache.http.client.methods.HttpUriRequest#setHeader()
The following examples show how to use
org.apache.http.client.methods.HttpUriRequest#setHeader() .
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: AuthzClientRequestFactory.java From devconf2019-authz with Apache License 2.0 | 6 votes |
@Override protected void postProcessHttpRequest(HttpUriRequest request) { KeycloakSecurityContext context = this.getKeycloakSecurityContext(); // TODO: Ideally should do it all automatically by some provided adapter/utility String currentRpt = rptStore.getRpt(context); if (currentRpt == null) { // Fallback to access token currentRpt = context.getTokenString(); } else { AccessToken parsedRpt = rptStore.getParsedRpt(context); if (!parsedRpt.isActive(10)) { // Just delete RPT and use accessToken instead. TODO: Will be good to have some "built-in" way to refresh RPT for clients log.info("Deleting expired RPT. Will need to obtain new when needed"); rptStore.deleteCurrentRpt(servletRequest); currentRpt = context.getTokenString(); } } request.setHeader(AUTHORIZATION_HEADER, "Bearer " + currentRpt); }
Example 2
Source File: AuthHttpClientTestCase.java From docker-java-api with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * 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 3
Source File: Request.java From nbp with Apache License 2.0 | 6 votes |
Object call(HttpUriRequest req) throws Exception { for (Map.Entry<String, String> entry : this.headers.entrySet()) { String k = entry.getKey(); String v = entry.getValue(); req.setHeader(k, v); } HttpResponse response = this.client.execute(req); int responseCode = response.getStatusLine().getStatusCode(); this.responseHeaders = response.getAllHeaders(); if (responseCode >= 300) { String reason = response.getStatusLine().getReasonPhrase(); throw new HttpException(responseCode, reason); } String result = EntityUtils.toString(response.getEntity(), "utf-8"); return this.handler.parseResponseBody(result); }
Example 4
Source File: AsyncHttpClient.java From Libraries-for-Android-Developers with MIT License | 5 votes |
/** * Puts a new request in queue as a new thread in pool to be executed * * @param client HttpClient to be used for request, can differ in single requests * @param contentType MIME body type, for POST and PUT requests, may be null * @param context Context of Android application, to hold the reference of request * @param httpContext HttpContext in which the request will be executed * @param responseHandler ResponseHandler or its subclass to put the response into * @param uriRequest instance of HttpUriRequest, which means it must be of HttpDelete, * HttpPost, HttpGet, HttpPut, etc. * @return RequestHandle of future request process */ protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) { if (contentType != null) { uriRequest.setHeader("Content-Type", contentType); } responseHandler.setRequestHeaders(uriRequest.getAllHeaders()); responseHandler.setRequestURI(uriRequest.getURI()); AsyncHttpRequest request = new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler); threadPool.submit(request); RequestHandle requestHandle = new RequestHandle(request); if (context != null) { // Add request to request map List<RequestHandle> requestList = requestMap.get(context); if (requestList == null) { requestList = new LinkedList<RequestHandle>(); requestMap.put(context, requestList); } requestList.add(requestHandle); Iterator<RequestHandle> iterator = requestList.iterator(); while (iterator.hasNext()) { if (iterator.next().shouldBeGarbageCollected()) { iterator.remove(); } } } return requestHandle; }
Example 5
Source File: AbstractRestServerTest.java From vxquery with Apache License 2.0 | 5 votes |
/** * Fetch the {@link QueryResultResponse} from query result endpoint once the * corresponding {@link QueryResultRequest} is given. * * @param resultRequest * {@link QueryResultRequest} * @param accepts * expected * * <pre> * Accepts * </pre> * * header in responses * @param method * Http Method to be used to send the request * @return query result response received * @throws Exception */ protected static QueryResultResponse getQueryResultResponse(QueryResultRequest resultRequest, String accepts, String method) throws Exception { URI uri = RestUtils.buildQueryResultURI(resultRequest, restIpAddress, restPort); CloseableHttpClient httpClient = HttpClients.custom().setConnectionTimeToLive(20, TimeUnit.SECONDS).build(); try { HttpUriRequest request = getRequest(uri, method); if (accepts != null) { request.setHeader(HttpHeaders.ACCEPT, accepts); } try (CloseableHttpResponse httpResponse = httpClient.execute(request)) { if (accepts != null) { Assert.assertEquals(accepts, httpResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue()); } Assert.assertEquals(httpResponse.getStatusLine().getStatusCode(), HttpResponseStatus.OK.code()); HttpEntity entity = httpResponse.getEntity(); Assert.assertNotNull(entity); String response = RestUtils.readEntity(entity); return RestUtils.mapEntity(response, QueryResultResponse.class, accepts); } } finally { HttpClientUtils.closeQuietly(httpClient); } }
Example 6
Source File: DcRestAdapter.java From io with Apache License 2.0 | 5 votes |
/** * リクエストボディを受け取る POSTメソッド. * @param url リクエスト対象URL * @param data 書き込むデータ * @param headers リクエストヘッダのハッシュマップ * @return DcResponse型 * @throws DcException DAO例外 */ public final DcResponse post(final String url, final String data, final HashMap<String, String> headers) throws DcException { String contentType = headers.get(HttpHeaders.CONTENT_TYPE); HttpUriRequest req = makePostRequest(url, data, contentType); for (Map.Entry<String, String> entry : headers.entrySet()) { req.setHeader(entry.getKey(), entry.getValue()); } req.addHeader("X-Dc-Version", DcCoreTestConfig.getCoreVersion()); debugHttpRequest(req, data); DcResponse res = request(req); return res; }
Example 7
Source File: HttpUtil.java From pulsar-manager with Apache License 2.0 | 5 votes |
public static String httpRequest(HttpUriRequest request, Map<String, String> header) { CloseableHttpResponse response = null; try { for (Map.Entry<String, String> entry: header.entrySet()) { request.setHeader(entry.getKey(), entry.getValue()); } if (httpClient == null ) { initHttpClient(); } response = httpClient.execute(request); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String strResult = EntityUtils.toString(response.getEntity()); response.close(); return strResult; } else { request.abort(); } } catch (Throwable cause) { log.error("http request exception message: {}, http request error stack: {}", cause.getMessage(), cause.getCause()); } finally { try{ if (response != null) { response.close(); } }catch (Exception e){ log.error("Don't handle exception: {}", e.getMessage()); } } return null; }
Example 8
Source File: BaselineClientIdentityTokenResolver.java From cougar with Apache License 2.0 | 5 votes |
@Override public void rewrite(List<IdentityToken> credentials, HttpUriRequest output) { if (credentials != null) { for (IdentityToken token : credentials) { try { String tokenName = SimpleIdentityTokenName.valueOf(token.getName()).name(); output.setHeader(TOKEN_PREFIX + tokenName, token.getValue()); } catch (IllegalArgumentException e) { /*ignore*/ } } } }
Example 9
Source File: RangeFileAsyncHttpResponseHandler.java From Android-Basics-Codes with Artistic License 2.0 | 5 votes |
public void updateRequestHeaders(HttpUriRequest uriRequest) { if (mFile.exists() && mFile.canWrite()) current = mFile.length(); if (current > 0) { append = true; uriRequest.setHeader("Range", "bytes=" + current + "-"); } }
Example 10
Source File: ImmersionHttpClient.java From letv with Apache License 2.0 | 5 votes |
private HttpResponse b0449щ0449щщ0449(HttpUriRequest httpUriRequest, Map map, int i) throws Exception { URI uri = httpUriRequest.getURI(); String trim = uri.getHost() != null ? uri.getHost().trim() : ""; if (trim.length() > 0) { httpUriRequest.setHeader("Host", trim); } if (map != null) { for (Object next : map.entrySet()) { if (((b04170417041704170417З + b0417ЗЗЗЗ0417) * b04170417041704170417З) % bЗ0417ЗЗЗ0417 != bЗЗЗЗЗ0417) { b04170417041704170417З = 81; bЗЗЗЗЗ0417 = 31; } Entry entry = (Entry) next; httpUriRequest.setHeader((String) entry.getKey(), (String) entry.getValue()); } } Header[] allHeaders = httpUriRequest.getAllHeaders(); Log.d(b043D043Dнн043Dн, "request URI [" + httpUriRequest.getURI() + "]"); for (Object obj : allHeaders) { Log.d(b043D043Dнн043Dн, "request header [" + obj.toString() + "]"); } HttpConnectionParams.setSoTimeout(this.bнн043Dн043Dн.getParams(), i); HttpResponse execute = this.bнн043Dн043Dн.execute(httpUriRequest); if (execute != null) { return execute; } throw new RuntimeException("Null response returned."); }
Example 11
Source File: DcRestAdapter.java From io with Apache License 2.0 | 5 votes |
/** * レスポンスボディを受け取るGETメソッド. * @param url リクエスト対象URL * @param headers リクエストヘッダのハッシュマップ * @return DcResponse型 * @throws DcException DAO例外 */ public final DcResponse getAcceptEncodingGzip(final String url, final HashMap<String, String> headers) throws DcException { HttpUriRequest req = new HttpGet(url); req.addHeader("Accept-Encoding", "gzip"); for (Map.Entry<String, String> entry : headers.entrySet()) { req.setHeader(entry.getKey(), entry.getValue()); } req.addHeader("X-Dc-Version", DcCoreTestConfig.getCoreVersion()); debugHttpRequest(req, ""); DcResponse res = this.request(req); return res; }
Example 12
Source File: RestAdapter.java From io with Apache License 2.0 | 5 votes |
/** * This is the GET method to receive the response body using headers (If-None-Match specified). * @param url Target Request URL * @param headers Request header * @param etag Etag value * @return DcResponse object * @throws DaoException Exception thrown */ public DcResponse get(String url, Map<String, String> headers, String etag) throws DaoException { HttpUriRequest req = new DcRequestBuilder().url(url).method(HttpMethods.GET).acceptEncoding("gzip") .token(getToken()).ifNoneMatch(etag).defaultHeaders(this.accessor.getDefaultHeaders()).build(); for (Map.Entry<String, String> entry : headers.entrySet()) { req.setHeader(entry.getKey(), entry.getValue()); } return this.request(req); }
Example 13
Source File: FileServiceTest.java From armeria with Apache License 2.0 | 4 votes |
private static void assert304NotModified( CloseableHttpClient hc, String baseUri, String path, String expectedETag, String expectedLastModified) throws IOException { final String uri = baseUri + path; // Test if the 'If-None-Match' header works as expected. (a single etag) final HttpUriRequest req1 = new HttpGet(uri); req1.setHeader(HttpHeaders.IF_NONE_MATCH, expectedETag); try (CloseableHttpResponse res = hc.execute(req1)) { assert304NotModified(res, expectedETag, expectedLastModified); } // Test if the 'If-None-Match' header works as expected. (multiple etags) final HttpUriRequest req2 = new HttpGet(uri); req2.setHeader(HttpHeaders.IF_NONE_MATCH, "\"an-etag-that-never-matches\", " + expectedETag); try (CloseableHttpResponse res = hc.execute(req2)) { assert304NotModified(res, expectedETag, expectedLastModified); } // Test if the 'If-None-Match' header works as expected. (an asterisk) final HttpUriRequest req3 = new HttpGet(uri); req3.setHeader(HttpHeaders.IF_NONE_MATCH, "*"); try (CloseableHttpResponse res = hc.execute(req3)) { assert304NotModified(res, expectedETag, expectedLastModified); } // Test if the 'If-Modified-Since' header works as expected. final HttpUriRequest req4 = new HttpGet(uri); req4.setHeader(HttpHeaders.IF_MODIFIED_SINCE, currentHttpDate()); try (CloseableHttpResponse res = hc.execute(req4)) { assert304NotModified(res, expectedETag, expectedLastModified); } // 'If-Modified-Since' should never be evaluated if 'If-None-Match' exists. final HttpUriRequest req5 = new HttpGet(uri); req5.setHeader(HttpHeaders.IF_NONE_MATCH, "\"an-etag-that-never-matches\""); req5.setHeader(HttpHeaders.IF_MODIFIED_SINCE, currentHttpDate()); try (CloseableHttpResponse res = hc.execute(req5)) { // Should not receive '304 Not Modified' because the etag did not match. assertStatusLine(res, "HTTP/1.1 200 OK"); // Read the content fully so that Apache HC does not close the connection prematurely. ByteStreams.exhaust(res.getEntity().getContent()); } }
Example 14
Source File: AsyncHttpClient.java From android-project-wo2b with Apache License 2.0 | 4 votes |
/** * Puts a new request in queue as a new thread in pool to be executed * * @param client HttpClient to be used for request, can differ in single requests * @param contentType MIME body type, for POST and PUT requests, may be null * @param context Context of Android application, to hold the reference of request * @param httpContext HttpContext in which the request will be executed * @param responseHandler ResponseHandler or its subclass to put the response into * @param uriRequest instance of HttpUriRequest, which means it must be of HttpDelete, * HttpPost, HttpGet, HttpPut, etc. * @return RequestHandle of future request process */ protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) { if (uriRequest == null) { throw new IllegalArgumentException("HttpUriRequest must not be null"); } if (responseHandler == null) { throw new IllegalArgumentException("ResponseHandler must not be null"); } if (responseHandler.getUseSynchronousMode()) { throw new IllegalArgumentException("Synchronous ResponseHandler used in AsyncHttpClient. You should create your response handler in a looper thread or use SyncHttpClient instead."); } if (contentType != null) { uriRequest.setHeader(HEADER_CONTENT_TYPE, contentType); } responseHandler.setRequestHeaders(uriRequest.getAllHeaders()); responseHandler.setRequestURI(uriRequest.getURI()); AsyncHttpRequest request = newAsyncHttpRequest(client, httpContext, uriRequest, contentType, responseHandler, context); threadPool.submit(request); RequestHandle requestHandle = new RequestHandle(request); if (context != null) { // Add request to request map List<RequestHandle> requestList = requestMap.get(context); synchronized (requestMap) { if (requestList == null) { requestList = Collections.synchronizedList(new LinkedList<RequestHandle>()); requestMap.put(context, requestList); } } if (responseHandler instanceof RangeFileAsyncHttpResponseHandler) ((RangeFileAsyncHttpResponseHandler) responseHandler).updateRequestHeaders(uriRequest); requestList.add(requestHandle); Iterator<RequestHandle> iterator = requestList.iterator(); while (iterator.hasNext()) { if (iterator.next().shouldBeGarbageCollected()) { iterator.remove(); } } } return requestHandle; }
Example 15
Source File: KeycloakConfidentialClientRequestFactory.java From smartling-keycloak-extras with Apache License 2.0 | 4 votes |
@Override protected void postProcessHttpRequest(HttpUriRequest request) { request.setHeader(HttpHeaders.AUTHORIZATION, this.createBasicAuthorizationHeader()); }
Example 16
Source File: TwitchStreamAudioSourceManager.java From lavaplayer with Apache License 2.0 | 4 votes |
private static HttpUriRequest addClientHeaders(HttpUriRequest request, String clientId) { request.setHeader("Client-ID", clientId); return request; }
Example 17
Source File: HttpClientStack.java From okulus with Apache License 2.0 | 4 votes |
private static void addHeaders(HttpUriRequest httpRequest, Map<String, String> headers) { for (String key : headers.keySet()) { httpRequest.setHeader(key, headers.get(key)); } }
Example 18
Source File: AsyncHttpClient.java From joyqueue with Apache License 2.0 | 4 votes |
public static void AsyncRequest(HttpUriRequest request, FutureCallback<HttpResponse> asyncCallBack){ httpclient.start(); request.setHeader("Content-Type", "application/json;charset=utf-8"); httpclient.execute(request,asyncCallBack); }
Example 19
Source File: HttpClientStack.java From jus with Apache License 2.0 | 4 votes |
private static void addHeaders(HttpUriRequest httpRequest, Map<String, String> headers) { for (String key : headers.keySet()) { httpRequest.setHeader(key, headers.get(key)); } }
Example 20
Source File: HTTPUtils.java From micro-integrator with Apache License 2.0 | 2 votes |
/** * Sets a HTTP header to the HTTP request. * * @param key HTTP header's name to set * @param value HTTP header's value to set * @param request HttpUriRequest to set header */ public static void setHTTPHeader(String key, String value, HttpUriRequest request) { request.setHeader(key, value); }