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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #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: 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 #12
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 #13
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 #14
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 #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: 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 #17
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 #18
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 #19
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 #20
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 #21
Source File: EveryRequestPlanner.java From vscrawler with Apache License 2.0 | 5 votes |
@Override public Proxy determineProxy(HttpHost host, HttpRequest request, HttpContext context, IPPool ipPool, CrawlerSession crawlerSession) { HttpClientContext httpClientContext = HttpClientContext.adapt(context); Proxy bind = (Proxy) context.getAttribute(VSCrawlerConstant.VSCRAWLER_AVPROXY_KEY); String accessUrl = null; if (request instanceof HttpRequestWrapper || request instanceof HttpGet) { accessUrl = HttpUriRequest.class.cast(request).getURI().toString(); } if (!PoolUtil.isDungProxyEnabled(httpClientContext)) { log.info("{}不会被代理", accessUrl); return null; } if (bind == null || bind.isDisable()) { bind = ipPool.getIP(host.getHostName(), accessUrl); } if (bind == null) { return null; } log.info("{} 当前使用IP为:{}:{}", host.getHostName(), bind.getIp(), bind.getPort()); // 将绑定IP放置到context,用于后置拦截器统计这个IP的使用情况 return bind; }
Example #22
Source File: IncomingLegacyMmsConnection.java From Silence with GNU General Public License v3.0 | 5 votes |
private HttpUriRequest constructRequest(Apn contentApn, boolean useProxy) throws IOException { HttpGetHC4 request = new HttpGetHC4(contentApn.getMmsc()); for (Header header : getBaseHeaders()) { request.addHeader(header); } if (useProxy) { HttpHost proxy = new HttpHost(contentApn.getProxy(), contentApn.getPort()); request.setConfig(RequestConfig.custom().setProxy(proxy).build()); } return request; }
Example #23
Source File: ActivitiClientService.java From activiti6-boot2 with Apache License 2.0 | 5 votes |
public ActivitiServiceException wrapException(Exception e, HttpUriRequest request) { if (e instanceof HttpHostConnectException) { return new ActivitiServiceException("Unable to connect to the Activiti server."); } else if (e instanceof ConnectTimeoutException) { return new ActivitiServiceException("Connection to the Activiti server timed out."); } else { // Use the raw exception message return new ActivitiServiceException(e.getClass().getName() + ": " + e.getMessage()); } }
Example #24
Source File: FlagsClient.java From vespa with Apache License 2.0 | 5 votes |
private <T> T executeRequest(HttpUriRequest request, ResponseHandler<T> handler) { try { return client.execute(request, handler); } catch (IOException e) { throw new UncheckedIOException(e); } }
Example #25
Source File: HttpClientWrapper.java From apigee-android-sdk with Apache License 2.0 | 5 votes |
@Override public <T> T execute(final HttpUriRequest request, final ResponseHandler<? extends T> responseHandler) throws IOException, ClientProtocolException { final HttpContext context = new BasicHttpContext(); return execute(request, responseHandler, context); }
Example #26
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 #27
Source File: TesterClient.java From vespa with Apache License 2.0 | 5 votes |
private HttpResponse execute(HttpUriRequest request, String messageIfRequestFails) { logger.log(Level.FINE, "Sending request to tester container " + request.getURI().toString()); try { return new ProxyResponse(httpClient.execute(request)); } catch (IOException e) { logger.warning(messageIfRequestFails + ": " + Exceptions.toMessageString(e)); return HttpErrorResponse.internalServerError(Exceptions.toMessageString(e)); } }
Example #28
Source File: HttpClientStack.java From volley_demo 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: HttpClientStackTest.java From volley with Apache License 2.0 | 5 votes |
@Test public void createPatchRequest() throws Exception { TestRequest.Patch request = new TestRequest.Patch(); assertEquals(request.getMethod(), Method.PATCH); HttpUriRequest httpRequest = HttpClientStack.createHttpRequest(request, null); assertTrue(httpRequest instanceof HttpPatch); }
Example #30
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()); } }