List of usage examples for org.apache.http.client.fluent Request Post
public static Request Post(final String uri)
From source file:org.wildfly.swarm.microprofile.jwtauth.providers.ProvidersMergingTest.java
@RunAsClient @Test// w w w . j a v a 2 s . c om public void shouldWorkWithAuthedPost() throws Exception { String response = Request.Post("http://localhost:8080/mpjwt/providers") .setHeader("Authorization", "Bearer " + createToken("MappedRole2")) .setHeader("Accept", MediaType.TEXT_PLAIN).execute().returnContent().asString(); Assert.assertEquals("original POST response", response); }
From source file:org.jspare.jsdbc.JsdbcTransportImpl.java
@Override public String execute(DataSource datasource, Credential credential, Optional<Domain> domain, String operation, int method, String data) throws JsdbcException { if (datasource == null) { throw new JsdbcException("DataSource not loaded"); }//from ww w .ja va2 s . c o m try { Request request = null; org.apache.http.client.fluent.Response response = null; String uriAddress = getUrlConnection(datasource, operation, Optional.of(domain.orElse(Domain.of(StringUtils.EMPTY)).domain())); if (method == RETRIEVE) { request = Request.Get(new URIBuilder(uriAddress).build().toString()); } else if (method == SEND) { request = Request.Post(new URIBuilder(uriAddress).build().toString()).bodyString(data, ContentType.APPLICATION_JSON); } else { throw new JsdbcException("Method called is not mapped"); } request.addHeader(AGENT_KEY, AGENT); response = buildAuthentication(request, datasource, credential).execute(); HttpResponse httpResponse = response.returnResponse(); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode < HttpStatus.SC_OK || statusCode >= HttpStatus.SC_MULTIPLE_CHOICES) { if (statusCode == HttpStatus.SC_BAD_REQUEST) { throw new JsdbcException("Authorization error, validate your credentials."); } if (statusCode == HttpStatus.SC_FORBIDDEN) { throw new JsdbcException("Forbidden access, validate your user roles."); } String content = IOUtils.toString(httpResponse.getEntity().getContent()); ErrorResult result = my(Serializer.class).fromJSON(content, ErrorResult.class); throw new CommandFailException(result); } return IOUtils.toString(httpResponse.getEntity().getContent()); } catch (Exception e) { log.error(e.getMessage(), e); throw new JsdbcException("JSDB Server Error"); } }
From source file:info.losd.galen.client.ApiClient.java
private Request request(ApiRequest req) { switch (req.getMethod()) { case GET://from w w w . jav a2 s.c o m return Request.Get(req.getUrl()); case POST: return Request.Post(req.getUrl()); default: throw new RuntimeException("Unimplemented ApiRequest type"); } }
From source file:com.example.cognitive.personality.DemoServlet.java
/** * Create and POST a request to the Personality Insights service * //w w w . ja v a2 s .com * @param req * the Http Servlet request * @param resp * the Http Servlet pesponse * @throws ServletException * the servlet exception * @throws IOException * Signals that an I/O exception has occurred. */ @Override protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { logger.info("doPost"); req.setCharacterEncoding("UTF-8"); // create the request String text = req.getParameter("text"); try { URI profileURI = new URI(baseURL + "/v2/profile").normalize(); Request profileRequest = Request.Post(profileURI).addHeader("Accept", "application/json") .bodyString(text, ContentType.TEXT_PLAIN); Executor executor = Executor.newInstance().auth(username, password); Response response = executor.execute(profileRequest); HttpResponse httpResponse = response.returnResponse(); resp.setStatus(httpResponse.getStatusLine().getStatusCode()); ServletOutputStream servletOutputStream = resp.getOutputStream(); httpResponse.getEntity().writeTo(servletOutputStream); servletOutputStream.flush(); servletOutputStream.close(); } catch (Exception e) { logger.log(Level.SEVERE, "Service error: " + e.getMessage(), e); resp.setStatus(HttpStatus.SC_BAD_GATEWAY); } }
From source file:com.github.piotrkot.resources.CompilerResourceTest.java
/** * POST authorization method should return name if appropriate. * @throws Exception If something fails. *//* w ww .j av a 2 s .c om*/ @Test public void testAuthenticate() throws Exception { final String uri = String.format("http://localhost:%d/compiler/auth", CompilerResourceTest.APP_RULE.getLocalPort()); Assert.assertEquals("test", Request.Post(uri).setHeader(OK_AUTH).execute().returnContent().asString()); // @checkstyle MagicNumber (2 lines) Assert.assertEquals(401L, (long) Request.Post(uri).setHeader(NOK_AUTH).execute().returnResponse() .getStatusLine().getStatusCode()); }
From source file:org.apache.sling.replication.transport.impl.PollingTransportHandler.java
@Override public void deliverPackageToEndpoint(ReplicationPackage replicationPackage, ReplicationEndpoint replicationEndpoint, ReplicationQueueProcessor responseProcessor) throws Exception { log.info("polling from {}", replicationEndpoint.getUri()); Executor executor = Executor.newInstance(); TransportAuthenticationContext context = new TransportAuthenticationContext(); context.addAttribute("endpoint", replicationEndpoint); executor = transportAuthenticationProvider.authenticate(executor, context); Request req = Request.Post(replicationEndpoint.getUri()) .addHeader(ReplicationHeader.ACTION.toString(), ReplicationActionType.POLL.getName()) .useExpectContinue();//from ww w . j av a 2 s .c om // TODO : add queue header int polls = pollItems; // continuously requests package streams as long as type header is received with the response (meaning there's a package of a certain type) HttpResponse httpResponse; while ((httpResponse = executor.execute(req).returnResponse()) .containsHeader(ReplicationHeader.TYPE.toString()) && polls != 0) { ReplicationQueueItem queueItem = readPackageHeaders(httpResponse); if (responseProcessor != null) responseProcessor.process("poll", queueItem); polls--; } }
From source file:org.mule.module.http.functional.listener.HttpListenerUrlEncodedTestCase.java
@Test public void invalidUrlEncodedParamsReturnInvalidRequestStatusCode() throws Exception { final Response response = Request.Post(getListenerUrl()) .body(new StringEntity("Invalid url encoded content")) .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED).execute(); final HttpResponse httpResponse = response.returnResponse(); assertThat(httpResponse.getStatusLine().getStatusCode(), equalTo(200)); assertThat(/*from www. jav a 2 s. c om*/ URLDecoder.decode(IOUtils.toString(httpResponse.getEntity().getContent()), Charsets.UTF_8.name()), is("Invalid url encoded content")); }
From source file:org.mule.module.http.functional.listener.HttpListenerResponseStreamingTestCase.java
protected void testResponseIsNotChunkedEncoding(String url, HttpVersion httpVersion) throws IOException { final Response response = Request.Post(url).version(httpVersion).connectTimeout(1000).socketTimeout(1000) .bodyByteArray(TEST_BODY.getBytes()).execute(); final HttpResponse httpResponse = response.returnResponse(); final Header transferEncodingHeader = httpResponse.getFirstHeader(TRANSFER_ENCODING); final Header contentLengthHeader = httpResponse.getFirstHeader(CONTENT_LENGTH); assertThat(contentLengthHeader, nullValue()); assertThat(transferEncodingHeader, is(nullValue())); assertThat(IOUtils.toString(httpResponse.getEntity().getContent()), is(TEST_BODY)); }
From source file:org.n52.youngs.harvest.PoxCswSource.java
@Override public Collection<SourceRecord> getRecords(long startPosition, long maxRecords, Report report) { log.debug("Requesting {} records from catalog starting at {}", maxRecords, startPosition); Collection<SourceRecord> records = Lists.newArrayList(); HttpEntity entity = createRequest(startPosition, maxRecords); try {/*from w w w . ja va2s . c o m*/ log.debug("GetRecords request: {}", EntityUtils.toString(entity)); String response = Request.Post(getEndpoint().toString()).body(entity) .addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_XML.getMimeType()) .addHeader(HttpHeaders.ACCEPT_CHARSET, Charsets.UTF_8.name()).execute().returnContent() .asString(Charsets.UTF_8); log.trace("Response: {}", response); JAXBElement<GetRecordsResponseType> jaxb_response = unmarshaller .unmarshal(new StreamSource(new StringReader(response)), GetRecordsResponseType.class); BigInteger numberOfRecordsReturned = jaxb_response.getValue().getSearchResults() .getNumberOfRecordsReturned(); log.debug("Got response with {} records", numberOfRecordsReturned); List<Object> nodes = jaxb_response.getValue().getSearchResults().getAny(); if (!nodes.isEmpty()) { log.debug("Found {} \"any\" nodes.", nodes.size()); nodes.stream().filter(n -> n instanceof Node).map(n -> (Node) n).map(n -> new NodeSourceRecord(n)) .forEach(records::add); } List<JAXBElement<? extends AbstractRecordType>> jaxb_records = jaxb_response.getValue() .getSearchResults().getAbstractRecord(); if (!jaxb_records.isEmpty()) { log.debug("Found {} \"AbstractRecordType\" records.", jaxb_records.size()); DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); jaxb_records.stream().map(type -> { return getNode(type, context, db); }).filter(Objects::nonNull).map(n -> new NodeSourceRecord(n)).forEach(records::add); } } catch (IOException | JAXBException | ParserConfigurationException e) { log.error("Could not retrieve records from endpoint {}", getEndpoint(), e); report.addMessage(String.format("Error retrieving record from endpoint %s: %s", this, e)); } log.debug("Decoded {} records", records.size()); return records; }
From source file:com.ctrip.infosec.rule.rest.RuleEngineRESTfulControllerTest.java
@Test @Ignore/*w w w . j a va2 s . com*/ public void testQuery() throws Exception { System.out.println("query"); String response = Request.Post("http://10.2.10.77:8080/ruleenginews/rule/query") .body(new StringEntity(JSON.toJSONString(fact), "UTF-8")).connectTimeout(1000).socketTimeout(5000) .execute().returnContent().asString(); System.out.println("response: " + response); ResponseEntity<String> responseEntity = rt.exchange("http://10.2.10.77:8080/ruleenginews/rule/query", HttpMethod.POST, new HttpEntity<String>(JSON.toJSONString(fact)), String.class); System.out.println("response: " + responseEntity.getBody()); }