Java Code Examples for org.apache.http.client.methods.HttpUriRequest#addHeader()
The following examples show how to use
org.apache.http.client.methods.HttpUriRequest#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: BaseSpringRestTestCase.java From flowable-engine with Apache License 2.0 | 6 votes |
protected CloseableHttpResponse internalExecuteRequest(HttpUriRequest request, int expectedStatusCode, boolean addJsonContentType) { try { if (addJsonContentType && request.getFirstHeader(HttpHeaders.CONTENT_TYPE) == null) { // Revert to default content-type request.addHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json")); } CloseableHttpResponse response = client.execute(request); assertThat(response.getStatusLine()).isNotNull(); int responseStatusCode = response.getStatusLine().getStatusCode(); if (expectedStatusCode != responseStatusCode) { LOGGER.info("Wrong status code : {}, but should be {}", responseStatusCode, expectedStatusCode); if (response.getEntity() != null) { LOGGER.info("Response body: {}", IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8)); } } assertThat(responseStatusCode).isEqualTo(expectedStatusCode); httpResponses.add(response); return response; } catch (IOException e) { throw new UncheckedIOException(e); } }
Example 2
Source File: SyncHttpClient.java From Mobike with Apache License 2.0 | 6 votes |
@Override protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) { if (contentType != null) { uriRequest.addHeader(AsyncHttpClient.HEADER_CONTENT_TYPE, contentType); } responseHandler.setUseSynchronousMode(true); /* * will execute the request directly */ newAsyncHttpRequest(client, httpContext, uriRequest, contentType, responseHandler, context).run(); // Return getUrl Request Handle that cannot be used to cancel the request // because it is already complete by the time this returns return new RequestHandle(null); }
Example 3
Source File: SyncHttpClient.java From Android-Basics-Codes with Artistic License 2.0 | 6 votes |
@Override protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) { if (contentType != null) { uriRequest.addHeader(AsyncHttpClient.HEADER_CONTENT_TYPE, contentType); } responseHandler.setUseSynchronousMode(true); /* * will execute the request directly */ newAsyncHttpRequest(client, httpContext, uriRequest, contentType, responseHandler, context).run(); // Return a Request Handle that cannot be used to cancel the request // because it is already complete by the time this returns return new RequestHandle(null); }
Example 4
Source File: DcRestAdapter.java From io with Apache License 2.0 | 6 votes |
/** * 共通のヘッダをセット. * @param req リクエストオブジェクト * @param contentType メディア種別 * @param accept Acceptヘッダ * @param etag Etag値 */ protected final void makeCommonHeaders(final HttpUriRequest req, final String contentType, final String accept, final String etag) { /* * String token = accessor.getAccessToken(); if (!token.isEmpty()) { req.setHeader("Authorization", * "Token token=\"" + token + "\""); } DaoConfig config = accessor.getDaoConfig(); String version = * config.getDcVersion(); if (!"".equals(version)) { req.setHeader("X-Tritium-Version", version); } */ if (contentType != null) { req.addHeader("Content-Type", contentType); } if (accept != null) { req.addHeader("Accept", accept); } if (etag != null) { req.addHeader("If-Match", etag); } }
Example 5
Source File: HttpTransportImpl.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
/** * handle httpRequest * * @param httpRequest * @return * @throws IOException */ private HttpResponse doRequest(HttpUriRequest httpRequest) throws IOException { //add header httpRequest.addHeader(HEADER_CONTENT_TYPE, "application/json"); httpRequest.addHeader(HEADER_USER_AGENT, "kie-client/1.0.0"); httpRequest.addHeader(HEADER_TENANT_NAME, "default"); //get Http response org.apache.http.HttpResponse response = httpClient.execute(httpRequest); int statusCode = response.getStatusLine().getStatusCode(); String messgae = response.getStatusLine().getReasonPhrase(); String context = null; if (response.getEntity() != null) { context = EntityUtils.toString(response.getEntity(), "UTF-8"); } return new HttpResponse(statusCode, messgae, context); }
Example 6
Source File: SyncHttpClient.java From Android-Basics-Codes with Artistic License 2.0 | 6 votes |
@Override protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) { if (contentType != null) { uriRequest.addHeader(AsyncHttpClient.HEADER_CONTENT_TYPE, contentType); } responseHandler.setUseSynchronousMode(true); /* * will execute the request directly */ newAsyncHttpRequest(client, httpContext, uriRequest, contentType, responseHandler, context).run(); // Return a Request Handle that cannot be used to cancel the request // because it is already complete by the time this returns return new RequestHandle(null); }
Example 7
Source File: Client.java From hbase with Apache License 2.0 | 5 votes |
/** * Execute a transaction method given a complete URI. * @param method the transaction method * @param headers HTTP header values to send * @param uri a properly urlencoded URI * @return the HTTP response code * @throws IOException */ public HttpResponse executeURI(HttpUriRequest method, Header[] headers, String uri) throws IOException { // method.setURI(new URI(uri, true)); for (Map.Entry<String, String> e: extraHeaders.entrySet()) { method.addHeader(e.getKey(), e.getValue()); } if (headers != null) { for (Header header: headers) { method.addHeader(header); } } long startTime = System.currentTimeMillis(); if (resp != null) EntityUtils.consumeQuietly(resp.getEntity()); resp = httpClient.execute(method); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { // Authentication error LOG.debug("Performing negotiation with the server."); negotiate(method, uri); resp = httpClient.execute(method); } long endTime = System.currentTimeMillis(); if (LOG.isTraceEnabled()) { LOG.trace(method.getMethod() + " " + uri + " " + resp.getStatusLine().getStatusCode() + " " + resp.getStatusLine().getReasonPhrase() + " in " + (endTime - startTime) + " ms"); } return resp; }
Example 8
Source File: ImpalaDispatchUtils.java From knox with Apache License 2.0 | 5 votes |
public static void addCredentialsToRequest(HttpUriRequest request) { String principal = SubjectUtils.getCurrentEffectivePrincipalName(); if ( principal != null ) { UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(principal, PASSWORD_PLACEHOLDER); try { request.addHeader(new BasicScheme().authenticate(credentials, request, null)); } catch (AuthenticationException e) { // impossible } } }
Example 9
Source File: CertificateAuthorityApiTest.java From vespa with Apache License 2.0 | 5 votes |
@Override protected <T> T execute(HttpUriRequest request, ResponseHandler<T> responseHandler) { request.addHeader("PRINCIPAL", principal.getName()); Optional.ofNullable(certificate).ifPresent(cert -> { var pem = X509CertificateUtils.toPem(certificate); request.addHeader("CERTIFICATE", StringUtilities.escape(pem)); }); return super.execute(request, responseHandler); }
Example 10
Source File: DcRestAdapter.java From io with Apache License 2.0 | 5 votes |
/** * レスポンスボディを受ける PUTメソッド. * @param url リクエスト対象URL * @param data 書き込むデータ * @param headers リクエストヘッダのハッシュマップ * @return DcResponse型 * @throws DcException DAO例外 */ public final DcResponse put(final String url, final String data, final HashMap<String, String> headers) throws DcException { String contentType = headers.get(HttpHeaders.CONTENT_TYPE); HttpUriRequest req = makePutRequest(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 11
Source File: Webdav4FileObject.java From commons-vfs with Apache License 2.0 | 5 votes |
private void setupRequest(final HttpUriRequest request) throws FileSystemException { // NOTE: *FileSystemConfigBuilder takes care of redirect option and user agent. request.addHeader("Cache-control", "no-cache"); request.addHeader("Cache-store", "no-store"); request.addHeader("Pragma", "no-cache"); request.addHeader("Expires", "0"); }
Example 12
Source File: HttpClientStack.java From volley with Apache License 2.0 | 5 votes |
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders); // add gzip support, not all request need gzip support if (request.isShouldGzip()) { httpRequest.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP); } addHeaders(httpRequest, additionalHeaders); addHeaders(httpRequest, request.getHeaders()); onPrepareRequest(httpRequest); HttpParams httpParams = httpRequest.getParams(); int timeoutMs = request.getTimeoutMs(); // TODO: Reevaluate this connection timeout based on more wide-scale // data collection and possibly different for wifi vs. 3G. HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIME_OUT_MS); HttpConnectionParams.setSoTimeout(httpParams, timeoutMs); HttpResponse response = mClient.execute(httpRequest); if (response != null) { final HttpEntity entity = response.getEntity(); if (entity == null) { return response; } final Header encoding = entity.getContentEncoding(); if (encoding != null) { for (HeaderElement element : encoding.getElements()) { if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) { response.setEntity(new InflatingEntity(response.getEntity())); break; } } } } return response; }
Example 13
Source File: DriveReadFeature.java From cyberduck with GNU General Public License v3.0 | 5 votes |
private InputStream read(final HttpUriRequest request, final Path file, final TransferStatus status) throws BackgroundException { request.addHeader(HTTP.CONTENT_TYPE, MEDIA_TYPE); if(status.isAppend()) { final HttpRange range = HttpRange.withStatus(status); final String header; if(-1 == range.getEnd()) { header = String.format("bytes=%d-", range.getStart()); } else { header = String.format("bytes=%d-%d", range.getStart(), range.getEnd()); } if(log.isDebugEnabled()) { log.debug(String.format("Add range header %s for file %s", header, file)); } request.addHeader(new BasicHeader(HttpHeaders.RANGE, header)); // Disable compression request.addHeader(new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "identity")); } final HttpClient client = session.getHttpClient(); try { final HttpResponse response = client.execute(request); switch(response.getStatusLine().getStatusCode()) { case HttpStatus.SC_OK: case HttpStatus.SC_PARTIAL_CONTENT: return new HttpMethodReleaseInputStream(response); default: throw new DefaultHttpResponseExceptionMappingService().map( new HttpResponseException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase())); } } catch(IOException e) { throw new DriveExceptionMappingService().map("Download {0} failed", e, file); } }
Example 14
Source File: ApacheHttpClientDelegate.java From docker-maven-plugin with Apache License 2.0 | 5 votes |
public <T> T post(String url, Object body, Map<String, String> headers, ResponseHandler<T> responseHandler, int... statusCodes) throws IOException { HttpUriRequest request = newPost(url, body); for (Entry<String, String> entry : headers.entrySet()) { request.addHeader(entry.getKey(), entry.getValue()); } return httpClient.execute(request, new StatusCodeCheckerResponseHandler<>(responseHandler, statusCodes)); }
Example 15
Source File: SyncHttpClient.java From Roid-Library with Apache License 2.0 | 5 votes |
@Override protected void sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, AsyncHttpResponseHandler responseHandler, Context context) { if (contentType != null) { uriRequest.addHeader("Content-Type", contentType); } /* * will execute the request directly */ new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler).run(); }
Example 16
Source File: HttpClient.java From rs-api with ISC License | 5 votes |
/** * Reads a {@link String} from a specified URL. * @param url The URL to request from. * @return The {@link String}. * @throws IOException If an I/O error occurs. */ private static String stringFrom(String url) throws IOException { Preconditions.checkNotNull(url); HttpUriRequest request = new HttpGet(url); request.addHeader("accept", "application/json"); request.addHeader("accept", "text/csv"); try (CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpResponse response = client.execute(request)) { return EntityUtils.toString(response.getEntity()); } }
Example 17
Source File: AttributesExampleControllerLiveTest.java From tutorials with MIT License | 5 votes |
@Test public void givenHeader_whenSet_thenRetrieveWithGet() throws Exception { final HttpUriRequest request = new HttpGet("http://localhost:9000/header-example"); request.addHeader("a-header","foobar"); try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create() .build() .execute(request);) { assertThat(httpResponse.getHeaders("a-header")[0].getValue()).isEqualTo("foobar"); } }
Example 18
Source File: RequestEntityRestStorageService.java From cyberduck with GNU General Public License v3.0 | 4 votes |
@Override protected HttpUriRequest setupConnection(final HTTP_METHOD method, final String bucketName, final String objectKey, final Map<String, String> requestParameters) throws S3ServiceException { final Host host = session.getHost(); // Apply default configuration if(S3Session.isAwsHostname(host.getHostname())) { // Check if not already set to accelerated endpoint if(properties.getStringProperty("s3service.s3-endpoint", preferences.getProperty("s3.hostname.default")).matches("s3-accelerate(\\.dualstack)?\\.amazonaws\\.com")) { log.debug("Skip adjusting endpoint with transfer acceleration"); } else { // Only for AWS set endpoint to region specific if(requestParameters == null || !requestParameters.containsKey("location")) { try { // Determine region for bucket using cache final Location.Name region = new S3LocationFeature(session, regionEndpointCache).getLocation(bucketName); if(Location.unknown == region) { log.warn(String.format("Failure determining bucket location for %s", bucketName)); } else { final String endpoint; if(preferences.getBoolean("s3.endpoint.dualstack.enable")) { endpoint = String.format(preferences.getProperty("s3.endpoint.format.ipv6"), region.getIdentifier()); } else { endpoint = String.format(preferences.getProperty("s3.endpoint.format.ipv4"), region.getIdentifier()); } if(log.isDebugEnabled()) { log.debug(String.format("Set endpoint to %s", endpoint)); } properties.setProperty("s3service.s3-endpoint", endpoint); } } catch(BackgroundException e) { // Ignore failure reading location for bucket log.error(String.format("Failure %s determining bucket location for %s", e, bucketName)); } } } } final HttpUriRequest request = super.setupConnection(method, bucketName, objectKey, requestParameters); if(preferences.getBoolean("s3.upload.expect-continue")) { if("PUT".equals(request.getMethod())) { // #7621 if(!properties.getBoolProperty("s3service.disable-expect-continue", false)) { request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE); } } } if(preferences.getBoolean("s3.bucket.requesterpays")) { // Only for AWS if(S3Session.isAwsHostname(host.getHostname())) { // Downloading Objects in Requester Pays Buckets if("GET".equals(request.getMethod()) || "POST".equals(request.getMethod())) { if(!properties.getBoolProperty("s3service.disable-request-payer", false)) { // For GET and POST requests, include x-amz-request-payer : requester in the header request.addHeader("x-amz-request-payer", "requester"); } } } } return request; }
Example 19
Source File: FinalHttp.java From Android-Basics-Codes with Artistic License 2.0 | 4 votes |
protected Object sendSyncRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType) { if(contentType != null) { uriRequest.addHeader("Content-Type", contentType); } return new SyncRequestHandler(client, httpContext,charset).sendRequest(uriRequest); }
Example 20
Source File: RequestUtil.java From jkube with Eclipse Public License 2.0 | 4 votes |
public static HttpUriRequest addDefaultHeaders(HttpUriRequest req) { req.addHeader(HEADER_ACCEPT, HEADER_ACCEPT_ALL); req.addHeader("Content-Type", "application/json"); return req; }