org.apache.http.HttpRequest Java Examples
The following examples show how to use
org.apache.http.HttpRequest.
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: RESTServiceConnectorTest.java From cloudstack with Apache License 2.0 | 6 votes |
@Test public void testExecuteCreateObjectWithParameters() throws Exception { final TestPojo newObject = new TestPojo(); newObject.setField("newValue"); final String newObjectJson = gson.toJson(newObject); final CloseableHttpResponse response = mock(CloseableHttpResponse.class); when(response.getEntity()).thenReturn(new StringEntity(newObjectJson)); when(response.getStatusLine()).thenReturn(HTTP_200_STATUS_LINE); final CloseableHttpClient httpClient = mock(CloseableHttpClient.class); when(httpClient.execute(any(HttpHost.class), any(HttpRequest.class), any(HttpClientContext.class))).thenReturn(response); final RestClient restClient = new BasicRestClient(httpClient, HttpClientContext.create(), "localhost"); final RESTServiceConnector connector = new RESTServiceConnector.Builder().client(restClient).build(); final TestPojo object = connector.executeCreateObject(newObject, "/somepath", DEFAULT_TEST_PARAMETERS); assertThat(object, notNullValue()); assertThat(object, equalTo(newObject)); verify(httpClient).execute(any(HttpHost.class), HttpUriRequestMethodMatcher.aMethod("POST"), any(HttpClientContext.class)); verify(httpClient).execute(any(HttpHost.class), HttpUriRequestPayloadMatcher.aPayload(newObjectJson), any(HttpClientContext.class)); verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("arg2=val2"), any(HttpClientContext.class)); verify(httpClient).execute(any(HttpHost.class), HttpUriRequestQueryMatcher.aQueryThatContains("arg1=val1"), any(HttpClientContext.class)); verify(response).close(); }
Example #2
Source File: HttpBasicPassTicketSchemeTest.java From api-layer with Eclipse Public License 2.0 | 6 votes |
@Test void givenJwtInCookie_whenApplyToRequest_thenJwtIsRemoved() { AuthenticationCommand command = getPassTicketCommand(); HttpRequest httpRequest = new HttpGet(); httpRequest.setHeader("cookie", authConfigurationProperties.getCookieProperties().getCookieName() + "=jwt;" + "abc=def" ); command.applyToRequest(httpRequest); Header[] headers = httpRequest.getHeaders("cookie"); assertNotNull(headers); assertEquals(1, headers.length); assertEquals("abc=def", headers[0].getValue()); }
Example #3
Source File: HTTPTestValidationHandler.java From camel-kafka-connector with Apache License 2.0 | 6 votes |
@Override public void handle(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) throws IOException { lock.lock(); try { HttpEntity entity = ((HttpEntityEnclosingRequest) httpRequest).getEntity(); String content = EntityUtils.toString(entity); replies.add(content); if (replies.size() == expected) { receivedExpectedMessages.signal(); } httpResponse.setStatusCode(HttpStatus.SC_OK); } finally { lock.unlock(); } }
Example #4
Source File: HttpClientConfigurer.java From Pushjet-Android with BSD 2-Clause "Simplified" License | 6 votes |
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); if (authState.getAuthScheme() != null || authState.hasAuthOptions()) { return; } // If no authState has been established and this is a PUT or POST request, add preemptive authorisation String requestMethod = request.getRequestLine().getMethod(); if (requestMethod.equals(HttpPut.METHOD_NAME) || requestMethod.equals(HttpPost.METHOD_NAME)) { CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); Credentials credentials = credentialsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort())); if (credentials == null) { throw new HttpException("No credentials for preemptive authentication"); } authState.update(authScheme, credentials); } }
Example #5
Source File: MartiDiceRoller.java From triplea with GNU General Public License v3.0 | 6 votes |
@Override public HttpUriRequest getRedirect( final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException { final URI uri = getLocationURI(request, response, context); final String method = request.getRequestLine().getMethod(); if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) { return new HttpHead(uri); } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) { return new HttpGet(uri); } else { final int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_TEMPORARY_REDIRECT || status == HttpStatus.SC_MOVED_PERMANENTLY || status == HttpStatus.SC_MOVED_TEMPORARILY) { return RequestBuilder.copy(request).setUri(uri).build(); } return new HttpGet(uri); } }
Example #6
Source File: DriverTest.java From esigate with Apache License 2.0 | 6 votes |
public void testForwardCookiesWithPorts() throws Exception { // Conf Properties properties = new PropertiesBuilder() // .set(Parameters.REMOTE_URL_BASE, "http://localhost:8080/") // .set(Parameters.PRESERVE_HOST, false) // .build(); mockConnectionManager = new MockConnectionManager() { @Override public HttpResponse execute(HttpRequest httpRequest) { Assert.assertNotNull(httpRequest.getFirstHeader("Cookie")); Assert.assertEquals("JSESSIONID=926E1C6A52804A625DFB0139962D4E13", httpRequest.getFirstHeader("Cookie") .getValue()); return new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "OK"); } }; Driver driver = createMockDriver(properties, mockConnectionManager); BasicClientCookie cookie = new BasicClientCookie("_JSESSIONID", "926E1C6A52804A625DFB0139962D4E13"); request = TestUtils.createIncomingRequest("http://127.0.0.1:8081/foobar.jsp").addCookie(cookie); driver.proxy("/foobar.jsp", request.build()); }
Example #7
Source File: WebRealmServiceTest.java From attic-polygene-java with Apache License 2.0 | 6 votes |
@Override public void process( final HttpRequest request, final HttpContext context ) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute( ClientContext.TARGET_AUTH_STATE ); CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute( ClientContext.CREDS_PROVIDER ); HttpHost targetHost = (HttpHost) context.getAttribute( ExecutionContext.HTTP_TARGET_HOST ); // If not auth scheme has been initialized yet if( authState.getAuthScheme() == null ) { AuthScope authScope = new AuthScope( targetHost.getHostName(), targetHost.getPort() ); // Obtain credentials matching the target host Credentials creds = credsProvider.getCredentials( authScope ); // If found, generate BasicScheme preemptively if( creds != null ) { authState.setAuthScheme( new BasicScheme() ); authState.setCredentials( creds ); } } }
Example #8
Source File: ArrayPayloadOf.java From docker-java-api with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Ctor. * * @param request The http request * @throws IllegalStateException if the request's payload cannot be read */ public ArrayPayloadOf(final HttpRequest request) { try (JsonReader reader = Json.createReader( ((HttpEntityEnclosingRequest) request).getEntity().getContent())) { if (request instanceof HttpEntityEnclosingRequest) { this.resources = reader.readArray().getValuesAs(JsonObject.class).iterator(); } else { this.resources = new ArrayList<JsonObject>().iterator(); } } catch (final IOException ex) { throw new IllegalStateException( "Cannot read request payload", ex ); } }
Example #9
Source File: ClusterServiceServletHttpHandler.java From cosmic with Apache License 2.0 | 6 votes |
private String handleDeliverPduMethodCall(final HttpRequest req) { s_logger.debug("Handling method Deliver PDU with request: " + req); final String pduSeq = (String) req.getParams().getParameter("pduSeq"); final String pduAckSeq = (String) req.getParams().getParameter("pduAckSeq"); final String sourcePeer = (String) req.getParams().getParameter("sourcePeer"); final String destPeer = (String) req.getParams().getParameter("destPeer"); final String agentId = (String) req.getParams().getParameter("agentId"); final String gsonPackage = (String) req.getParams().getParameter("gsonPackage"); final String stopOnError = (String) req.getParams().getParameter("stopOnError"); final String pduType = (String) req.getParams().getParameter("pduType"); final ClusterServicePdu pdu = new ClusterServicePdu(); pdu.setSourcePeer(sourcePeer); pdu.setDestPeer(destPeer); pdu.setAgentId(Long.parseLong(agentId)); pdu.setSequenceId(Long.parseLong(pduSeq)); pdu.setAckSequenceId(Long.parseLong(pduAckSeq)); pdu.setJsonPackage(gsonPackage); pdu.setStopOnError("1".equals(stopOnError)); pdu.setPduType(Integer.parseInt(pduType)); manager.OnReceiveClusterServicePdu(pdu); return "true"; }
Example #10
Source File: HttpClientManagerImpl.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
/** * Creates absolute request URI with full path from passed in context. */ @Nonnull private URI getRequestURI(final HttpContext context) { final HttpClientContext clientContext = HttpClientContext.adapt(context); final HttpRequest httpRequest = clientContext.getRequest(); final HttpHost target = clientContext.getTargetHost(); try { URI uri; if (httpRequest instanceof HttpUriRequest) { uri = ((HttpUriRequest) httpRequest).getURI(); } else { uri = URI.create(httpRequest.getRequestLine().getUri()); } return uri.isAbsolute() ? uri : URIUtils.resolve(URI.create(target.toURI()), uri); } catch (Exception e) { log.warn("Could not create absolute request URI", e); return URI.create(target.toURI()); } }
Example #11
Source File: MenuSetCompilingLanguagesActionHandler.java From Repeat with Apache License 2.0 | 6 votes |
@Override protected Void handleAllowedRequestWithBackend(HttpRequest request, HttpAsyncExchange exchange, HttpContext context) throws HttpException, IOException { Map<String, String> params = HttpServerUtilities.parseSimplePostParameters(request); if (params == null) { return HttpServerUtilities.prepareHttpResponse(exchange, 400, "Failed to parse POST parameters."); } String indexString = params.get("index"); if (indexString == null || !NumberUtility.isNonNegativeInteger(indexString)) { return HttpServerUtilities.prepareHttpResponse(exchange, 400, "Index must be provided as non-negative integer."); } Language language = Language.identify(Integer.parseInt(indexString)); if (language == null) { return HttpServerUtilities.prepareHttpResponse(exchange, 400, "Language index " + indexString + " unknown."); } try { JsonNode data = taskSourceCodeFragmentHandler.render(language); backEndHolder.setCompilingLanguage(language); return HttpServerUtilities.prepareJsonResponse(exchange, 200, data); } catch (RenderException e) { return HttpServerUtilities.prepareTextResponse(exchange, 500, "Failed to render page: " + e.getMessage()); } }
Example #12
Source File: ToggleIPCServiceLaunchAtStartupHandler.java From Repeat with Apache License 2.0 | 6 votes |
@Override protected Void handleAllowedRequestWithBackend(HttpRequest request, HttpAsyncExchange exchange, HttpContext context) throws HttpException, IOException { Map<String, String> params = HttpServerUtilities.parseSimplePostParameters(request); if (params == null) { return HttpServerUtilities.prepareHttpResponse(exchange, 500, "Unable to get POST paramters."); } IIPCService service = CommonTask.getIPCService(params); if (service == null) { return HttpServerUtilities.prepareHttpResponse(exchange, 500, "Unable to get IPC service."); } service.setLaunchAtStartup(!service.isLaunchAtStartup()); return renderedIpcServices(exchange); }
Example #13
Source File: OpenstackNetworkingUtil.java From onos with Apache License 2.0 | 6 votes |
/** * Deserializes raw payload into HttpRequest object. * * @param rawData raw http payload * @return HttpRequest object */ public static HttpRequest parseHttpRequest(byte[] rawData) { SessionInputBufferImpl sessionInputBuffer = new SessionInputBufferImpl( new HttpTransportMetricsImpl(), HTTP_PAYLOAD_BUFFER); sessionInputBuffer.bind(new ByteArrayInputStream(rawData)); DefaultHttpRequestParser requestParser = new DefaultHttpRequestParser(sessionInputBuffer); try { return requestParser.parse(); } catch (IOException | HttpException e) { log.warn("Failed to parse HttpRequest, due to {}", e); } return null; }
Example #14
Source File: RequestEntityRestStorageService.java From cyberduck with GNU General Public License v3.0 | 6 votes |
public RequestEntityRestStorageService(final S3Session session, final HttpClientBuilder configuration) { super(null, new PreferencesUseragentProvider().get(), null, toProperties(session.getHost(), session.getSignatureVersion())); this.session = session; this.properties = this.getJetS3tProperties(); // Client configuration configuration.disableContentCompression(); configuration.setRetryHandler(new S3HttpRequestRetryHandler(this, preferences.getInteger("http.connections.retry"))); configuration.setRedirectStrategy(new DefaultRedirectStrategy() { @Override public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException { if(response.containsHeader("x-amz-bucket-region")) { final String host = ((HttpUriRequest) request).getURI().getHost(); if(!StringUtils.equals(session.getHost().getHostname(), host)) { regionEndpointCache.putRegionForBucketName( StringUtils.split(StringUtils.removeEnd(((HttpUriRequest) request).getURI().getHost(), session.getHost().getHostname()), ".")[0], response.getFirstHeader("x-amz-bucket-region").getValue()); } } return super.getRedirect(request, response, context); } }); this.setHttpClient(configuration.build()); }
Example #15
Source File: UsingWithRestAssuredTest.java From curl-logger with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { Options options = Options.builder() .printSingleliner() .targetPlatform(Platform.UNIX) .useShortForm() .updateCurl(curl -> curl .removeHeader("Host") .removeHeader("User-Agent") .removeHeader("Connection")) .build(); try { curlConsumer.accept(new Http2Curl(options).generateCurl(request)); } catch (Exception e) { throw new RuntimeException(e); } }
Example #16
Source File: JolokiaClientFactory.java From hawkular-agent with Apache License 2.0 | 6 votes |
@Override public Header authenticate(Credentials credentials, HttpRequest request, HttpContext context) throws AuthenticationException { Args.notNull(credentials, "Credentials"); Args.notNull(request, "HTTP request"); // the bearer token is stored in the password field, not credentials.getUserPrincipal().getName() String bearerToken = credentials.getPassword(); CharArrayBuffer buffer = new CharArrayBuffer(64); if (isProxy()) { buffer.append("Proxy-Authorization"); } else { buffer.append("Authorization"); } buffer.append(": Bearer "); buffer.append(bearerToken); return new BufferedHeader(buffer); }
Example #17
Source File: LocalRequestTest.java From logbook with MIT License | 5 votes |
@Test void shouldHandleDuplicateHeaders() { final HttpRequest delegate = post("/"); delegate.addHeader("Content-Type", "text/plain;"); delegate.addHeader("Content-Type", "text/plain;"); final LocalRequest unit = unit(delegate); assertThat(unit.getHeaders(), aMapWithSize(1)); assertThat(unit.getHeaders().get("Content-Type"), hasSize(2)); }
Example #18
Source File: RetryHandler.java From NetDiscovery with Apache License 2.0 | 5 votes |
@Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= 3) {// 如果已经重试了3次,就放弃 return false; } if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试 return true; } if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常 return false; } if (exception instanceof InterruptedIOException) {// 超时 return true; } if (exception instanceof UnknownHostException) {// 目标服务器不可达 return false; } if (exception instanceof ConnectTimeoutException) {// 连接被拒绝 return false; } if (exception instanceof SSLException) {// ssl握手异常 return false; } HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); // 如果请求是幂等的,就再次尝试 return !(request instanceof HttpEntityEnclosingRequest); }
Example #19
Source File: ClientUtils.java From org.hl7.fhir.core with Apache License 2.0 | 5 votes |
private void setAuth(HttpRequest httpget) { if (password != null) { try { byte[] b = Base64.encodeBase64((username+":"+password).getBytes("ASCII")); String b64 = new String(b, StandardCharsets.US_ASCII); httpget.setHeader("Authorization", "Basic " + b64); } catch (UnsupportedEncodingException e) { } } }
Example #20
Source File: HttpHandlerWithBackend.java From Repeat with Apache License 2.0 | 5 votes |
@Override public void handle(HttpRequest request, HttpAsyncExchange exchange, HttpContext context) throws HttpException, IOException { if (backEndHolder == null) { LOGGER.warning("Missing backend..."); HttpServerUtilities.prepareTextResponse(exchange, 500, ""); return; } handleWithBackend(request, exchange, context); }
Example #21
Source File: HttpRequestHelper.java From esigate with Apache License 2.0 | 5 votes |
public static String getFirstHeader(String name, HttpRequest request) { final Header header = request.getFirstHeader(name); String headerValue = null; if (header != null) { headerValue = header.getValue(); } return headerValue; }
Example #22
Source File: AuthHandler.java From brooklyn-server with Apache License 2.0 | 5 votes |
@Override public void handle(HttpRequest request, HttpResponse response, HttpContext context) { String creds = (String) context.getAttribute("creds"); if (creds == null || !creds.equals(getExpectedCredentials())) { response.setStatusCode(HttpStatus.SC_UNAUTHORIZED); } else { response.setEntity(new ByteArrayEntity(responseBody)); } }
Example #23
Source File: HttpTest.java From Inside_Android_Testing with Apache License 2.0 | 5 votes |
@Test public void testGet_shouldApplyCorrectHeaders() throws Exception { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("foo", "bar"); http.get("www.example.com", headers, null, null); HttpRequest sentHttpRequest = Robolectric.getSentHttpRequest(0); assertThat(sentHttpRequest.getHeaders("foo")[0].getValue(), equalTo("bar")); }
Example #24
Source File: CachedResponseSuitabilityChecker.java From apigee-android-sdk with Apache License 2.0 | 5 votes |
private boolean hasValidDateField(HttpRequest request, String headerName) { for (Header h : request.getHeaders(headerName)) { try { DateUtils.parseDate(h.getValue()); return true; } catch (DateParseException dpe) { // ignore malformed dates } } return false; }
Example #25
Source File: HttpServerUtilities.java From Repeat with Apache License 2.0 | 5 votes |
public static Map<String, String> parseSimplePostParameters(HttpRequest request) { byte[] content = getPostContent(request); if (content == null) { LOGGER.warning("Failed to get POST content."); return null; } return getSimplePostParameters(content); }
Example #26
Source File: HttpAsyncRequestProducerWrapper.java From apm-agent-java with Apache License 2.0 | 5 votes |
@Override public HttpRequest generateRequest() throws IOException, HttpException { // first read the volatile, span will become visible as a result HttpRequest request = delegate.generateRequest(); if (request != null) { RequestLine requestLine = request.getRequestLine(); if (requestLine != null) { String method = requestLine.getMethod(); span.withName(method).appendToName(" "); span.getContext().getHttp().withMethod(method).withUrl(requestLine.getUri()); } span.propagateTraceContext(request, headerSetter); } HttpHost host = getTarget(); //noinspection ConstantConditions if (host != null) { String hostname = host.getHostName(); if (hostname != null) { span.appendToName(hostname); HttpClientHelper.setDestinationServiceDetails(span, host.getSchemeName(), hostname, host.getPort()); } } //noinspection ConstantConditions return request; }
Example #27
Source File: TracingHttpAsyncClientBuilder.java From brave with Apache License 2.0 | 5 votes |
@Override public void process(HttpRequest request, HttpContext context) { TraceContext parent = (TraceContext) context.getAttribute(TraceContext.class.getName()); HttpRequestWrapper wrapper = new HttpRequestWrapper(request, context); Span span = handler.handleSendWithParent(wrapper, parent); parseTargetAddress(wrapper.target, span); context.setAttribute(Span.class.getName(), span); context.setAttribute(Scope.class.getName(), currentTraceContext.newScope(span.context())); }
Example #28
Source File: TestHttpRequestHandler.java From brooklyn-server with Apache License 2.0 | 5 votes |
@Override public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { for (Header h : headers) { response.setHeader(h); } response.setStatusCode(responseCode); response.setEntity(entity); }
Example #29
Source File: WingtipsApacheHttpClientUtilTest.java From wingtips with Apache License 2.0 | 5 votes |
@Before public void beforeMethod() { requestMock = mock(HttpRequest.class); requestLineMock = mock(RequestLine.class); doReturn(requestLineMock).when(requestMock).getRequestLine(); }
Example #30
Source File: HttpClientUtil.java From lucene-solr with Apache License 2.0 | 5 votes |
@Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { if (!request.containsHeader("Accept-Encoding")) { request.addHeader("Accept-Encoding", "gzip, deflate"); } }