List of usage examples for org.apache.http.client.fluent Request Post
public static Request Post(final String uri)
From source file:org.apache.james.jmap.methods.integration.cucumber.UploadStepdefs.java
@When("^\"([^\"]*)\" upload a content without content type$") public void userUploadContentWithoutContentType(String username) throws Throwable { AccessToken accessToken = userStepdefs.tokenByUser.get(username); Request request = Request.Post(uploadUri).bodyByteArray("some text".getBytes(Charsets.UTF_8)); if (accessToken != null) { request.addHeader("Authorization", accessToken.serialize()); }//from w w w . j av a 2 s. com response = request.execute().returnResponse(); }
From source file:org.jboss.arquillian.container.was.wlp_remote_8_5.WLPRestClient.java
/** * Uses the rest api to upload an application binary to the dropins folder * of WLP to allow the server automatically deploy it. * /*from w w w. ja v a2 s .c o m*/ * @param archive * @throws ClientProtocolException * @throws IOException */ public void deploy(File archive) throws ClientProtocolException, IOException { if (log.isLoggable(Level.FINER)) { log.entering(className, "deploy"); } String deployPath = String.format("${wlp.user.dir}/servers/%s/dropins/%s", configuration.getServerName(), archive.getName()); String serverRestEndpoint = String.format("https://%s:%d%s%s", configuration.getHostName(), configuration.getHttpsPort(), FILE_ENDPOINT, URLEncoder.encode(deployPath, UTF_8)); HttpResponse result = executor.execute(Request.Post(serverRestEndpoint).useExpectContinue() .version(HttpVersion.HTTP_1_1).bodyFile(archive, ContentType.DEFAULT_BINARY)).returnResponse(); if (log.isLoggable(Level.FINE)) { log.fine("While deploying file " + archive.getName() + ", server returned response: " + result.getStatusLine().getStatusCode()); } if (!isSuccessful(result)) { throw new ClientProtocolException( "Could not deploy application to server, server returned response: " + result); } if (log.isLoggable(Level.FINER)) { log.exiting(className, "deploy"); } }
From source file:com.ibm.watson.ta.retail.DemoServlet.java
/** * Create and POST a request to the Watson service * * @param req//from w ww . j ava2 s. c o m * the Http Servlet request * @param resp * the Http Servlet response * @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 { req.setCharacterEncoding("UTF-8"); try { String queryStr = req.getQueryString(); String url = baseURL + "/v1/dilemmas"; if (queryStr != null) { url += "?" + queryStr; } URI uri = new URI(url).normalize(); logger.info("posting to " + url); Request newReq = Request.Post(uri); newReq.addHeader("Accept", "application/json"); InputStreamEntity entity = new InputStreamEntity(req.getInputStream()); newReq.bodyString(EntityUtils.toString(entity, "UTF-8"), ContentType.APPLICATION_JSON); Executor executor = this.buildExecutor(uri); Response response = executor.execute(newReq); HttpResponse httpResponse = response.returnResponse(); resp.setStatus(httpResponse.getStatusLine().getStatusCode()); ServletOutputStream servletOutputStream = resp.getOutputStream(); httpResponse.getEntity().writeTo(servletOutputStream); servletOutputStream.flush(); servletOutputStream.close(); logger.info("post done"); } catch (Exception e) { // Log something and return an error message logger.log(Level.SEVERE, "got error: " + e.getMessage(), e); resp.setStatus(HttpStatus.SC_BAD_GATEWAY); } }
From source file:com.softinstigate.restheart.integrationtest.SecurityIT.java
@Test public void testPostUnauthenticated() throws Exception { // *** POST coll1 Response resp = unauthExecutor.execute(Request.Post(collection1Uri).bodyString("{a:1}", halCT) .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE)); check("check post coll1 unauthorized", resp, HttpStatus.SC_UNAUTHORIZED); // *** GET coll2 resp = unauthExecutor.execute(Request.Post(collection2Uri).bodyString("{a:1}", halCT) .addHeader(Headers.CONTENT_TYPE_STRING, Representation.HAL_JSON_MEDIA_TYPE)); check("check post coll2b unauthorized", resp, HttpStatus.SC_UNAUTHORIZED); }
From source file:com.github.piotrkot.resources.CompilerResourceTest.java
/** * POST upload file method should be successful. * @throws Exception If something fails. *///from w ww . j a v a 2 s . c o m @Test public void testCompileSources() throws Exception { final String uri = String.format("http://localhost:%d/compiler/source", CompilerResourceTest.APP_RULE.getLocalPort()); Assert.assertTrue(HTTP_RESP_OK.contains(Request.Post(uri).setHeader(OK_AUTH) .body(MultipartEntityBuilder.create() .addBinaryBody("file", new ByteArrayInputStream("hello".getBytes()), ContentType.DEFAULT_BINARY, "noname") .build()) .execute().returnResponse().getStatusLine().getStatusCode())); }
From source file:edu.jhuapl.dorset.http.apache.ApacheHttpClient.java
private Response post(HttpRequest request) throws IOException { Request apacheRequest = Request.Post(request.getUrl()); if (request.getBody() != null) { ContentType ct = ContentType.create(request.getContentType().getMimeType(), request.getContentType().getCharset()); apacheRequest.bodyString(request.getBody(), ct); } else if (request.getBodyForm() != null) { apacheRequest.bodyForm(buildFormBody(request.getBodyForm())); }/*from w w w. j a va 2 s. co m*/ prepareRequest(apacheRequest); return apacheRequest.execute(); }
From source file:com.ctrip.infosec.rule.resource.hystrix.DataProxyQueryCommand.java
@Override protected Map<String, Object> run() throws Exception { DataProxyRequest request = new DataProxyRequest(); request.setServiceName(serviceName); request.setOperationName(operationName); request.setParams(params);//from ww w . ja v a 2 s . c o m List<DataProxyRequest> requests = new ArrayList<>(); requests.add(request); DataProxyResponse response = null; if (VENUS.equals(apiMode)) { DataProxyVenusService dataProxyVenusService = SpringContextHolder.getBean(DataProxyVenusService.class); List<DataProxyResponse> responses = dataProxyVenusService.dataproxyQueries(requests); if (responses == null || responses.size() < 1) { return null; } response = responses.get(0); if (response.getRtnCode() != 0) { logger.warn(Contexts.getLogPrefix() + "invoke DataProxy.queryForMap fault. RtnCode=" + response.getRtnCode() + ", RtnMessage=" + response.getMessage()); return null; } } else { String responseTxt = Request.Post(urlPrefix + "/rest/dataproxy/query") .body(new StringEntity(JSON.toJSONString(request), ContentType.APPLICATION_JSON)).execute() .returnContent().asString(); response = JSON.parseObject(responseTxt, DataProxyResponse.class); } if (response != null) { if (response.getRtnCode() == 0) { return response.getResult(); } else { logger.warn(Contexts.getLogPrefix() + "DataProxy. RtnCode=" + response.getRtnCode() + ", RtnMessage=" + response.getMessage()); } } return Collections.EMPTY_MAP; }
From source file:net.bis5.slack.command.gcal.SlashCommandApi.java
@RequestMapping(path = "/execute", method = RequestMethod.POST) public ResponseEntity<String> execute(@ModelAttribute RequestPayload payload) { log.info("Request: " + payload.toString()); EventRequest event = payload.createEvent(); log.info("Parsed Request: " + event.toString()); try {//w ww . j ava 2s. co m Event result = client.events().insert(config.getTargetCalendarId(), createEvent(event)).execute(); log.info("Event Create Result: " + result.toString()); ResponsePayload response = new ResponsePayload(); Date date = toDate(event.getDate().atStartOfDay()); Date start = toDate(LocalDateTime.of(event.getDate(), event.getFrom())); Date end = toDate(LocalDateTime.of(event.getDate(), event.getTo())); String user = payload.getUser_name(); String title = event.getTitle(); response.setText(String.format( "%s?????\n: %tY/%tm/%td\n: %tH:%tM\n: %tH:%tM\n??: %s", // user, date, date, date, start, start, end, end, title)); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { ObjectMapper mapper = new ObjectMapper(); String responseBody = mapper.writeValueAsString(response); log.info("Response Payload: " + responseBody); Request.Post(payload.getResponse_url()).bodyString(responseBody, ContentType.APPLICATION_JSON) .execute(); } return ResponseEntity.ok(null); } catch (IOException ex) { log.error(ex.toString()); return ResponseEntity.ok(ex.getMessage()); // OK?????????? } }
From source file:com.ibm.watson.ta.retail.TAProxyServlet.java
/** * Create and POST a request to the Watson service * * @param req//from ww w . java2 s .c om * the Http Servlet request * @param resp * the Http Servlet response * @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 { req.setCharacterEncoding("UTF-8"); try { String reqURI = req.getRequestURI(); String endpoint = reqURI.substring(reqURI.lastIndexOf('/') + 1); String url = baseURL + "/v1/" + endpoint; // concatenate query params String queryStr = req.getQueryString(); if (queryStr != null) { url += "?" + queryStr; } URI uri = new URI(url).normalize(); logger.info("posting to " + url); Request newReq = Request.Post(uri); newReq.addHeader("Accept", "application/json"); String metadata = req.getHeader("x-watson-metadata"); if (metadata != null) { metadata += "client-ip:" + req.getRemoteAddr(); newReq.addHeader("x-watson-metadata", metadata); } InputStreamEntity entity = new InputStreamEntity(req.getInputStream()); newReq.bodyString(EntityUtils.toString(entity, "UTF-8"), ContentType.APPLICATION_JSON); Executor executor = this.buildExecutor(uri); Response response = executor.execute(newReq); HttpResponse httpResponse = response.returnResponse(); resp.setStatus(httpResponse.getStatusLine().getStatusCode()); ServletOutputStream servletOutputStream = resp.getOutputStream(); httpResponse.getEntity().writeTo(servletOutputStream); servletOutputStream.flush(); servletOutputStream.close(); logger.info("post done"); } catch (Exception e) { // Log something and return an error message logger.log(Level.SEVERE, "got error: " + e.getMessage(), e); resp.setStatus(HttpStatus.SC_BAD_GATEWAY); } }
From source file:org.mule.module.http.functional.listener.HttpListenerUrlEncodedTestCase.java
@Test public void urlEncodedMultiValueParamsHasOldValues() throws Exception { final Response response = Request.Post(getListenerUrl()) .bodyForm(new BasicNameValuePair(PARAM_1_NAME, PARAM_1_VALUE), new BasicNameValuePair(PARAM_2_NAME, PARAM_2_VALUE_1), new BasicNameValuePair(PARAM_2_NAME, PARAM_2_VALUE_2)) .execute();/* ww w . jav a 2s. c o m*/ final MuleMessage receivedMessage = muleContext.getClient().request(VM_OUTPUT_ENDPOINT, 1000); assertThat(receivedMessage.getPayload(), IsInstanceOf.instanceOf(ParameterMap.class)); ParameterMap payloadAsMap = (ParameterMap) receivedMessage.getPayload(); assertThat(payloadAsMap.size(), is(2)); assertThat(payloadAsMap.get(PARAM_1_NAME), Is.<Object>is(PARAM_1_VALUE)); assertThat(payloadAsMap.getAll(PARAM_2_NAME).size(), Is.is(2)); assertThat(payloadAsMap.getAll(PARAM_2_NAME).get(0), Is.is(PARAM_2_VALUE_1)); assertThat(payloadAsMap.getAll(PARAM_2_NAME).get(1), Is.is(PARAM_2_VALUE_2)); compareParameterMaps(response, payloadAsMap); }