org.apache.http.client.methods.HttpUriRequest Java Examples
The following examples show how to use
org.apache.http.client.methods.HttpUriRequest.
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: SecurityClientRequestFactory.java From dolphin-platform with Apache License 2.0 | 6 votes |
@Override protected void postProcessHttpRequest(HttpUriRequest request) { final String token = securityTokenSupplier.get(); if(token != null && !token.isEmpty() && !request.containsHeader(AUTHORIZATION_HEADER)) { LOG.debug("adding auth header"); request.setHeader(AUTHORIZATION_HEADER, BEARER + token); } final String realm = realmSupplier.get(); if(realm != null && !realm.isEmpty() && !request.containsHeader(REALM_NAME_HEADER)) { LOG.debug("adding realm header"); request.setHeader(REALM_NAME_HEADER, realm); } final String appName = appNameSupplier.get(); if(appName != null && !appName.isEmpty() && !request.containsHeader(APPLICATION_NAME_HEADER)) { LOG.debug("adding app name header"); request.setHeader(APPLICATION_NAME_HEADER, appName); } }
Example #2
Source File: CustomRedirectStrategy.java From webmagic with Apache License 2.0 | 6 votes |
@Override public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException { URI uri = getLocationURI(request, response, context); String method = request.getRequestLine().getMethod(); if ("post".equalsIgnoreCase(method)) { try { HttpRequestWrapper httpRequestWrapper = (HttpRequestWrapper) request; httpRequestWrapper.setURI(uri); httpRequestWrapper.removeHeaders("Content-Length"); return httpRequestWrapper; } catch (Exception e) { logger.error("强转为HttpRequestWrapper出错"); } return new HttpPost(uri); } else { return new HttpGet(uri); } }
Example #3
Source File: EscrowOperationsRecover.java From InflatableDonkey with MIT License | 6 votes |
static NSDictionary recover(HttpClient httpClient, EscrowProxyRequestFactory requests, byte[] uid, byte[] tag, byte[] m1) throws IOException { logger.debug("-- recover() - uid: 0x{} tag: 0x{} m1: 0x{}", Hex.toHexString(uid), Hex.toHexString(tag), Hex.toHexString(m1)); /* SRP-6a RECOVER Failures will deplete attempts (we have 10 attempts max). Server will abort on an invalid M1 or present us with, amongst other things, M2 which we can verify (or not). */ HttpUriRequest recoverRequest = requests.recover(m1, uid, tag); NSDictionary response = httpClient.execute(recoverRequest, RESPONSE_HANDLER); logger.debug("-- recover() - response: {}", response.toXMLPropertyList()); return response; }
Example #4
Source File: UnixHttpClientTestCase.java From docker-java-api with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * UnixHttpClient can execute the HttpUriRequest with the given * context. * @throws IOException If something goes wrong. */ @Test public void executesUriRequestWithContext() throws IOException { final HttpUriRequest req = Mockito.mock(HttpUriRequest.class); final HttpContext context = Mockito.mock(HttpContext.class); final HttpResponse resp = Mockito.mock(HttpResponse.class); final HttpClient decorated = Mockito.mock(HttpClient.class); Mockito.when( decorated.execute(req, context) ).thenReturn(resp); final HttpClient unix = new UnixHttpClient(() -> decorated); MatcherAssert.assertThat( unix.execute(req, context), Matchers.is(resp) ); Mockito.verify( decorated, Mockito.times(1) ).execute(req, context); }
Example #5
Source File: HCRequestFactoryTest.java From log4j2-elasticsearch with Apache License 2.0 | 6 votes |
@Test public void createsPostRequest() throws IOException, URISyntaxException { // given HCRequestFactory factory = createDefaultTestObject(); String expectedUrl = UUID.randomUUID().toString(); Request request = createDefaultMockRequest(expectedUrl, "POST"); // when HttpUriRequest result = factory.create(expectedUrl, request); // then assertTrue(result instanceof HttpPost); assertEquals(result.getURI(), new URI(expectedUrl)); }
Example #6
Source File: HttpUriRequestBuilderTest.java From cloudstack with Apache License 2.0 | 6 votes |
@Test public void testBuildRequestWithParameters() throws Exception { final HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("key1", "value1"); final HttpUriRequest request = HttpUriRequestBuilder.create() .method(HttpMethods.GET) .path("/path") .parameters(parameters) .build(); assertThat(request, notNullValue()); assertThat(request.getURI().getPath(), equalTo("/path")); assertThat(request.getURI().getQuery(), equalTo("key1=value1")); assertThat(request.getURI().getScheme(), nullValue()); assertThat(request.getURI().getHost(), nullValue()); assertThat(request.getMethod(), equalTo(HttpGet.METHOD_NAME)); }
Example #7
Source File: RestTask.java From android-discourse with Apache License 2.0 | 6 votes |
private HttpUriRequest createRequest() throws URISyntaxException, UnsupportedEncodingException { String host = Session.getInstance().getConfig().getSite(); Uri.Builder uriBuilder = new Uri.Builder(); uriBuilder.scheme(host.contains(".us.com") ? "http" : "https"); uriBuilder.encodedAuthority(host); uriBuilder.path(urlPath); if (method == RestMethod.GET) return requestWithQueryString(new HttpGet(), uriBuilder); else if (method == RestMethod.DELETE) return requestWithQueryString(new HttpDelete(), uriBuilder); else if (method == RestMethod.POST) return requestWithEntity(new HttpPost(), uriBuilder); else if (method == RestMethod.PUT) return requestWithEntity(new HttpPut(), uriBuilder); else throw new IllegalArgumentException("Method must be one of [GET, POST, PUT, DELETE], but was " + method); }
Example #8
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 #9
Source File: DefaultHttpClient.java From aws-xray-sdk-java with Apache License 2.0 | 6 votes |
@Override public CloseableHttpResponse execute( HttpUriRequest request, HttpContext context) throws IOException, ClientProtocolException { Subsegment subsegment = getRecorder().beginSubsegment(TracedHttpClient.determineTarget(request).getHostName()); try { if (null != subsegment) { TracedHttpClient.addRequestInformation(subsegment, request, TracedHttpClient.getUrl(request)); } CloseableHttpResponse response = super.execute(request, context); if (null != subsegment) { TracedResponseHandler.addResponseInformation(subsegment, response); } return response; } catch (Exception e) { if (null != subsegment) { subsegment.addException(e); } throw e; } finally { if (null != subsegment) { getRecorder().endSubsegment(); } } }
Example #10
Source File: DownloadHttpArtifact.java From vertx-deploy-tools with Apache License 2.0 | 6 votes |
@Override public Observable<T> executeAsync(T request) { CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(config.getHttpAuthUser(), config.getHttpAuthPassword()); provider.setCredentials(AuthScope.ANY, credentials); final URI location = config.getNexusUrl().resolve(config.getNexusUrl().getPath() + "/" + request.getRemoteLocation()); try (CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build()) { LOG.info("[{} - {}]: Downloaded artifact {} to {}.", logConstant, request.getId(), request.getModuleId(), request.getLocalPath(config.getArtifactRepo())); HttpUriRequest get = new HttpGet(location); CloseableHttpResponse response = client.execute(get); response.getEntity().writeTo(new FileOutputStream(request.getLocalPath(config.getArtifactRepo()).toFile())); } catch (IOException e) { LOG.error("[{} - {}]: Error downloading artifact -> {}, {}", logConstant, request.getId(), e.getMessage(), e); throw new IllegalStateException(e); } return just(request); }
Example #11
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 #12
Source File: Client.java From geoportal-server-harvester with Apache License 2.0 | 6 votes |
private <T> T execute(HttpUriRequest req, Class<T> clazz) throws IOException, URISyntaxException { try (CloseableHttpResponse httpResponse = httpClient.execute(req); InputStream contentStream = httpResponse.getEntity().getContent();) { String reasonMessage = httpResponse.getStatusLine().getReasonPhrase(); String responseContent = IOUtils.toString(contentStream, "UTF-8"); LOG.trace(String.format("RESPONSE: %s, %s", responseContent, reasonMessage)); if (httpResponse.getStatusLine().getStatusCode() >= 400) { T value = null; try { value = mapper.readValue(responseContent, clazz); } catch (Exception ex) { throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase()); } if (value == null) { throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase()); } return value; } return mapper.readValue(responseContent, clazz); } }
Example #13
Source File: NameServerServiceImpl.java From joyqueue with Apache License 2.0 | 6 votes |
@Deprecated private String onResponse(CloseableHttpResponse response, HttpUriRequest request) throws Exception { try { int statusCode = response.getStatusLine().getStatusCode(); if (HttpStatus.SC_OK != statusCode) { String message = String.format("monitorUrl [%s],reuqest[%s] error code [%s],response[%s]", request.getURI().toString(), request.toString(), statusCode, EntityUtils.toString(response.getEntity())); throw new Exception(message); } String result = EntityUtils.toString(response.getEntity()); logger.info("request[{}] response[{}]", request.toString(), result); return result; } finally { response.close(); } }
Example #14
Source File: ErrorResponseException.java From nomad-java-sdk with Mozilla Public License 2.0 | 6 votes |
static ErrorResponseException signaledInStatus(HttpUriRequest request, HttpResponse response) { String rawEntity; String errorMessage; int errorCode; try { rawEntity = EntityUtils.toString(response.getEntity()); errorMessage = rawEntity; errorCode = response.getStatusLine().getStatusCode(); } catch (IOException e) { rawEntity = null; errorMessage = "!!!ERROR GETTING ERROR MESSAGE FROM RESPONSE ENTITY: " + e + "!!!"; errorCode = 0; } String errorLocation = "response status " + response.getStatusLine(); return new ErrorResponseException(request, errorLocation, errorMessage, errorCode, rawEntity); }
Example #15
Source File: AtlasApiHaDispatch.java From knox with Apache License 2.0 | 6 votes |
@Override protected void executeRequest(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest, HttpServletResponse outboundResponse) throws IOException { HttpResponse inboundResponse = null; try { inboundResponse = executeOutboundRequest(outboundRequest); int statusCode = inboundResponse.getStatusLine().getStatusCode(); Header originalLocationHeader = inboundResponse.getFirstHeader("Location"); if ((statusCode == HttpServletResponse.SC_MOVED_TEMPORARILY || statusCode == HttpServletResponse.SC_TEMPORARY_REDIRECT) && originalLocationHeader != null) { inboundResponse.removeHeaders("Location"); failoverRequest(outboundRequest, inboundRequest, outboundResponse, inboundResponse, new Exception("Atlas HA redirection")); } writeOutboundResponse(outboundRequest, inboundRequest, outboundResponse, inboundResponse); } catch (IOException e) { LOG.errorConnectingToServer(outboundRequest.getURI().toString(), e); failoverRequest(outboundRequest, inboundRequest, outboundResponse, inboundResponse, e); } }
Example #16
Source File: ResultErrorHandler.java From springboot-security-wechat with Apache License 2.0 | 6 votes |
protected void doHandle(String uriId,HttpUriRequest request,Object result){ if(this.isError(result)){ String content = null; if(request instanceof HttpEntityEnclosingRequestBase){ HttpEntityEnclosingRequestBase request_base = (HttpEntityEnclosingRequestBase)request; HttpEntity entity = request_base.getEntity(); //MULTIPART_FORM_DATA 请求类型判断 if(entity.getContentType().toString().indexOf(ContentType.MULTIPART_FORM_DATA.getMimeType()) == -1){ try { content = EntityUtils.toString(entity); } catch (Exception e) { e.printStackTrace(); } } if(logger.isErrorEnabled()){ logger.error("URI[{}] {} Content:{} Result:{}", uriId, request.getURI(), content == null ? "multipart_form_data" : content, result == null? null : JsonUtil.toJSONString(result)); } } this.handle(uriId,request.getURI().toString(),content,result); } }
Example #17
Source File: NomadApiClient.java From nomad-java-sdk with Mozilla Public License 2.0 | 6 votes |
private HttpUriRequest buildRequest( RequestBuilder requestBuilder, @Nullable RequestOptions options ) { String region = getConfig().getRegion(); String namespace = getConfig().getNamespace(); String authToken = getConfig().getAuthToken(); if (options != null) { if (options.getRegion() != null) region = options.getRegion(); if (options.getNamespace() != null) namespace = options.getNamespace(); if (options.getAuthToken() != null) authToken = options.getAuthToken(); } if (region != null && !region.isEmpty()) requestBuilder.addParameter("region", region); if (namespace != null && !namespace.isEmpty()) requestBuilder.addParameter("namespace", namespace); if (authToken != null && !authToken.isEmpty()) requestBuilder.addHeader("X-Nomad-Token", authToken); return requestBuilder.build(); }
Example #18
Source File: ConfigurableDispatchTest.java From knox with Apache License 2.0 | 6 votes |
@Test( timeout = TestUtils.SHORT_TIMEOUT ) public void testRequestExcludeHeadersDefault() { ConfigurableDispatch dispatch = new ConfigurableDispatch(); Map<String, String> headers = new HashMap<>(); headers.put(HttpHeaders.AUTHORIZATION, "Basic ..."); headers.put(HttpHeaders.ACCEPT, "abc"); headers.put("TEST", "test"); HttpServletRequest inboundRequest = EasyMock.createNiceMock(HttpServletRequest.class); EasyMock.expect(inboundRequest.getHeaderNames()).andReturn(Collections.enumeration(headers.keySet())).anyTimes(); Capture<String> capturedArgument = Capture.newInstance(); EasyMock.expect(inboundRequest.getHeader(EasyMock.capture(capturedArgument))) .andAnswer(() -> headers.get(capturedArgument.getValue())).anyTimes(); EasyMock.replay(inboundRequest); HttpUriRequest outboundRequest = new HttpGet(); dispatch.copyRequestHeaderFields(outboundRequest, inboundRequest); Header[] outboundRequestHeaders = outboundRequest.getAllHeaders(); assertThat(outboundRequestHeaders.length, is(2)); assertThat(outboundRequestHeaders[0].getName(), is(HttpHeaders.ACCEPT)); assertThat(outboundRequestHeaders[1].getName(), is("TEST")); }
Example #19
Source File: HttpClientExecutable.java From cougar with Apache License 2.0 | 6 votes |
@Override protected void sendRequest(HttpUriRequest httpMethod, ExecutionObserver obs, OperationDefinition operationDefinition) { try { final HttpResponse response = client.execute(httpMethod); if (LOGGER.isDebugEnabled()) { final int statusCode = response.getStatusLine().getStatusCode(); LOGGER.debug("Received http response code of " + statusCode + " in reply to request to " + httpMethod.getURI()); } processResponse(new CougarHttpResponse(response), obs, operationDefinition); } catch (Exception e) { processException(obs, e, httpMethod.getURI().toString()); } }
Example #20
Source File: SofaBootRpcAllTest.java From sofa-rpc-boot-projects with Apache License 2.0 | 6 votes |
@Test public void testRestSwaggerAddService() throws IOException { List<BindingParam> bindingParams = new ArrayList<>(); bindingParams.add(new RestBindingParam()); ServiceParam serviceParam = new ServiceParam(); serviceParam.setInterfaceType(AddService.class); serviceParam.setInstance((AddService) () -> "Hello"); serviceParam.setBindingParams(bindingParams); ServiceClient serviceClient = clientFactory.getClient(ServiceClient.class); serviceClient.service(serviceParam); HttpClient httpClient = HttpClientBuilder.create().build(); HttpUriRequest request = new HttpGet("http://localhost:8341/swagger/openapi"); HttpResponse response = httpClient.execute(request); Assert.assertEquals(200, response.getStatusLine().getStatusCode()); Assert.assertTrue(EntityUtils.toString(response.getEntity()).contains("/webapi/add_service")); }
Example #21
Source File: FileServiceTest.java From armeria with Apache License 2.0 | 5 votes |
@ParameterizedTest @ArgumentsSource(BaseUriProvider.class) void testFileSystemGetUtf8(String baseUri) throws Exception { final Path barFile = tmpDir.resolve("¢.txt"); final String expectedContentA = "¢"; writeFile(barFile, expectedContentA); try (CloseableHttpClient hc = HttpClients.createMinimal()) { final HttpUriRequest req = new HttpGet(baseUri + "/fs/%C2%A2.txt"); try (CloseableHttpResponse res = hc.execute(req)) { assert200Ok(res, "text/plain", expectedContentA); } } }
Example #22
Source File: MockHttpClient.java From device-database with Apache License 2.0 | 5 votes |
@Override public HttpResponse execute(HttpUriRequest request, HttpContext context) { requestExecuted = request; StatusLine statusLine = new BasicStatusLine( new ProtocolVersion("HTTP", 1, 1), mStatusCode, ""); HttpResponse response = new BasicHttpResponse(statusLine); response.setEntity(mResponseEntity); return response; }
Example #23
Source File: HttpClientStackTest.java From device-database with Apache License 2.0 | 5 votes |
@Test public void createDeprecatedPostRequest() throws Exception { TestRequest.DeprecatedPost request = new TestRequest.DeprecatedPost(); assertEquals(request.getMethod(), Method.DEPRECATED_GET_OR_POST); HttpUriRequest httpRequest = HttpClientStack.createHttpRequest(request, null); assertTrue(httpRequest instanceof HttpPost); }
Example #24
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 #25
Source File: HttpClientCougarRequestFactoryTest.java From cougar with Apache License 2.0 | 5 votes |
@Test public void shouldAddNewHeadersWithoutDeleteTheExistingHeaders() { HttpUriRequest request = new HttpGet(); request.setHeader("X-UUID", "1111-111-111-111"); List<Header> headers = new ArrayList<>(1); headers.add(new BasicHeader("NEW-HEADER", "value")); factory.addHeaders(request, headers); assertEquals(2, request.getAllHeaders().length); assertEquals("1111-111-111-111", request.getFirstHeader("X-UUID").getValue()); assertEquals("value", request.getFirstHeader("NEW-HEADER").getValue()); }
Example #26
Source File: SimpleHttpClient.java From micro-integrator with Apache License 2.0 | 5 votes |
private void setHeaders(Map<String, String> headers, HttpUriRequest request) { if (headers != null && headers.size() > 0) { for (Map.Entry<String, String> header : headers.entrySet()) { request.setHeader(header.getKey(), header.getValue()); } } }
Example #27
Source File: BaseClient.java From galaxy-sdk-java with Apache License 2.0 | 5 votes |
protected HttpUriRequest makeJsonEntityRequest(Object requestEntity, URI uri, HttpMethod method) throws IOException { Gson gson = new Gson(); String jsonStr = ""; if (requestEntity != null) { jsonStr = gson.toJson(requestEntity); } StringEntity entity = new StringEntity(jsonStr, ContentType.APPLICATION_JSON); return prepareRequestMethod(uri, method, ContentType.APPLICATION_JSON, null, null, entity); }
Example #28
Source File: HttpClientStack.java From device-database 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); 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, 5000); HttpConnectionParams.setSoTimeout(httpParams, timeoutMs); return mClient.execute(httpRequest); }
Example #29
Source File: GalaxyFDSClient.java From galaxy-fds-sdk-java with Apache License 2.0 | 5 votes |
@Override public void deleteTimestampAntiStealingLinkConfig(String bucketName) throws GalaxyFDSClientException { URI uri = formatUri(fdsConfig.getBaseUri(), bucketName, (SubResource[]) null); HashMap<String, String> params = new HashMap<String, String>(); params.put("antiStealingLink", ""); HttpUriRequest httpRequest = fdsHttpClient.prepareRequestMethod(uri, HttpMethod.DELETE, null, null, params, null, null); HttpResponse response = fdsHttpClient.executeHttpRequest(httpRequest, Action.DeleteAntiStealingLinkConfig); fdsHttpClient.processResponse(response, null, "Delete anti-stealing-link config bucket [" + bucketName + "]"); }
Example #30
Source File: HttpRequestMatcher.java From cosmic with Apache License 2.0 | 5 votes |
private boolean checkUri(final HttpUriRequest actual) { if (wanted instanceof HttpUriRequest) { final String wantedQuery = ((HttpUriRequest) wanted).getURI().getQuery(); final String actualQuery = actual.getURI().getQuery(); return equalsString(wantedQuery, actualQuery); } else { return wanted == actual; } }