List of usage examples for org.apache.http.client.fluent Request Post
public static Request Post(final String uri)
From source file:org.n52.youngs.test.SpatialSearchIT.java
/** records with bounding boxes: //from w w w . j av a 2 s. c o m urn:uuid:9a669547-b69b-469f-a11f-2d875366bbdc: <ows:BoundingBox crs="urn:x-ogc:def:crs:EPSG:6.11:4326"> <ows:LowerCorner>44.792 -6.171</ows:LowerCorner> <ows:UpperCorner>51.126 -2.228</ows:UpperCorner> </ows:BoundingBox> urn:uuid:94bc9c83-97f6-4b40-9eb8-a8e8787a5c63: <ows:BoundingBox crs="urn:x-ogc:def:crs:EPSG:6.11:4326"> <ows:LowerCorner>47.595 -4.097</ows:LowerCorner> <ows:UpperCorner>51.217 0.889</ows:UpperCorner> </ows:BoundingBox> urn:uuid:1ef30a8b-876d-4828-9246-c37ab4510bbd: <ows:BoundingBox crs="urn:x-ogc:def:crs:EPSG:6.11:4326"> <ows:LowerCorner>60.042 13.754</ows:LowerCorner> <ows:UpperCorner>68.410 17.920</ows:UpperCorner> </ows:BoundingBox> */ @Test public void spatialQueryPointSearch() throws Exception { String endpoint = "http://localhost:9200/" + mapping.getIndex() + "/" + mapping.getType() + "/_search?pretty"; String pointInOneRecordQuery = "{" + " \"query\":{" + " \"filtered\":{" + " \"query\":{" + " \"match_all\":{" + "" + " }" + " }," + " \"filter\":{" + " \"geo_shape\":{" + " \"location\":{" + " \"shape\":{" + " \"type\":\"point\"," + " \"coordinates\":[" + " 62.0," + " 15.0" + " ]" + " }" + " }" + " }" + " }" + " }" + " }" + "}"; String searchWithPointResponse = Request.Post(endpoint) .bodyString(pointInOneRecordQuery, ContentType.APPLICATION_JSON).execute().returnContent() .asString(); assertThat("correct number of records found", searchWithPointResponse, hasJsonPath("hits.total", is(1))); assertThat("ids are contained", searchWithPointResponse, allOf(containsString("urn:uuid:1ef30a8b-876d-4828-9246-c37ab4510bbd"), not(containsString("urn:uuid:9a669547-b69b-469f-a11f-2d875366bbdc")), not(containsString("urn:uuid:94bc9c83-97f6-4b40-9eb8-a8e8787a5c63")))); }
From source file:com.twosigma.beaker.NamespaceClient.java
public Object set4(String name, Object value, Boolean unset, Boolean sync) throws ClientProtocolException, IOException { Form form = Form.form().add("name", name).add("sync", sync.toString()).add("session", this.session); if (!unset) { StringWriter sw = new StringWriter(); JsonGenerator jgen = objectMapper.get().getJsonFactory().createJsonGenerator(sw); if (!objectSerializerProvider.get().writeObject(value, jgen, true)) form.add("value", value.toString()); else {//from w w w . j av a 2 s . c o m jgen.flush(); form.add("value", sw.toString()); } } String reply = Request.Post(urlBase + "/set").addHeader("Authorization", auth).bodyForm(form.build()) .execute().returnContent().asString(); if (!reply.equals("ok")) { throw new RuntimeException(reply); } return value; }
From source file:org.apache.james.jmap.methods.integration.cucumber.SetMailboxesMethodStepdefs.java
@When("^moving mailbox \"([^\"]*)\" to \"([^\"]*)\"$") public void movingMailbox(String actualMailboxPath, String newParentMailboxPath) throws Throwable { String username = userStepdefs.lastConnectedUser; Mailbox mailbox = mainStepdefs.jmapServer.serverProbe().getMailbox("#private", username, actualMailboxPath); String mailboxId = mailbox.getMailboxId().serialize(); Mailbox parent = mainStepdefs.jmapServer.serverProbe().getMailbox("#private", username, newParentMailboxPath);//from www . j ava 2 s. c o m String parentId = parent.getMailboxId().serialize(); String requestBody = "[" + " [ \"setMailboxes\"," + " {" + " \"update\": {" + " \"" + mailboxId + "\" : {" + " \"parentId\" : \"" + parentId + "\"" + " }" + " }" + " }," + " \"#0\"" + " ]" + "]"; Request.Post(mainStepdefs.baseUri().setPath("/jmap").build()) .addHeader("Authorization", userStepdefs.tokenByUser.get(username).serialize()) .bodyString(requestBody, ContentType.APPLICATION_JSON).execute().discardContent(); }
From source file:com.ibm.watson.WatsonTranslate.java
public String translate(String text) { String tweetTranslation = text; if (watsonLangPair != null && text != null && !text.equals("")) { List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("txt", text)); qparams.add(new BasicNameValuePair("sid", watsonLangPair)); qparams.add(new BasicNameValuePair("rt", "text")); try {//from w w w .j ava 2s . com Executor executor = Executor.newInstance(); URI serviceURI = new URI(baseURLTranslation).normalize(); String auth = usernameTranslation + ":" + passwordTranslation; byte[] response = executor .execute(Request.Post(serviceURI) .addHeader("Authorization", "Basic " + Base64.encodeBase64String(auth.getBytes())) .bodyString(URLEncodedUtils.format(qparams, "utf-8"), ContentType.APPLICATION_FORM_URLENCODED) .connectTimeout(15 * 1000)) .returnContent().asBytes(); tweetTranslation = new String(response, "UTF-8"); logger.debug("Translated {} to {}", text, tweetTranslation); } catch (Exception e) { logger.error("Watson error: {} on text: {}", e.getMessage(), text); } } return tweetTranslation; }
From source file:api.WebServiceCommand.java
@Override public CommandStatus execute() { CommandStatus status = new CommandStatus(); try {//from w w w .j a v a2 s.co m switch (this.httpVerb) { case "POST": status = Request.Post(this.uri).version(this.version).useExpectContinue() .connectTimeout(this.connectionTimeout).socketTimeout(this.socketTimeout) .bodyString(this.postString, this.contentType).execute() .handleResponse(new ResponseHandler<HTTPCommandStatus>() { @Override public HTTPCommandStatus handleResponse(HttpResponse hr) throws ClientProtocolException, IOException { HTTPCommandStatus cs = new HTTPCommandStatus(); StatusLine statusLine = hr.getStatusLine(); HttpEntity entity = hr.getEntity(); cs.setHttpCode(statusLine.getStatusCode()); cs.setEntity(entity); cs.setStderr(statusLine.getReasonPhrase()); return cs; } }); case "GET": default: status = Request.Get(this.uri).version(this.version).connectTimeout(this.connectionTimeout) .socketTimeout(this.socketTimeout).execute() .handleResponse(new ResponseHandler<HTTPCommandStatus>() { @Override public HTTPCommandStatus handleResponse(HttpResponse hr) throws ClientProtocolException, IOException { HTTPCommandStatus cs = new HTTPCommandStatus(); StatusLine statusLine = hr.getStatusLine(); HttpEntity entity = hr.getEntity(); cs.setHttpCode(statusLine.getStatusCode()); cs.setEntity(entity); cs.setStderr(statusLine.getReasonPhrase()); return cs; } }); break; } if (this.debug) { System.out.println(" CODE RETURNED: '" + status.getStatus() + "'."); System.out.println("CONTOUT RETURNED: '" + status.getStdout() + "'."); System.out.println("CONTERR RETURNED: '" + status.getStderr() + "'."); } } catch (ClientProtocolException ex) { status.setEnded(ResponseTypes.CONFIG_ERROR.ordinal()); System.out.println(ex.getMessage()); } catch (IOException ex) { status.setEnded(ResponseTypes.FAIL.ordinal()); System.out.println(ex.getMessage()); } return status; }
From source file:com.yfiton.notifiers.pushbullet.PushbulletNotifier.java
@Override protected AccessTokenData requestAccessTokenData(AuthorizationData authorizationData) throws NotificationException { try {//from w w w . j a va 2s . c o m String authorizationCode = authorizationData.getAuthorizationCode(); String response = Request.Post(getAccessTokenUrl(authorizationCode).get()) .bodyForm(Form.form().add("client_id", getClientId()).add("client_secret", getClientSecret()) .add("code", authorizationCode).add("grant_type", "authorization_code").build()) .execute().returnContent().asString(); JsonObject json = new JsonParser().parse(response).getAsJsonObject(); String accessToken = json.get("access_token").getAsString(); String tokenType = json.get("token_type").getAsString(); return new AccessTokenData(accessToken, ImmutableMap.of("tokenType", tokenType)); } catch (IOException e) { throw new NotificationException(e); } }
From source file:org.apache.sling.replication.transport.impl.HttpTransportHandler.java
private void deliverPackage(Executor executor, ReplicationPackage replicationPackage, ReplicationEndpoint replicationEndpoint) throws IOException { String type = replicationPackage.getType(); Request req = Request.Post(replicationEndpoint.getUri()).useExpectContinue(); if (useCustomHeaders) { String[] customizedHeaders = getCustomizedHeaders(customHeaders, replicationPackage.getAction(), replicationPackage.getPaths()); for (String header : customizedHeaders) { addHeader(req, header);//from w ww .j a v a 2s. c om } } else { req.addHeader(ReplicationHeader.TYPE.toString(), type); } InputStream inputStream = null; Response response = null; try { if (useCustomBody) { String body = customBody == null ? "" : customBody; inputStream = new ByteArrayInputStream(body.getBytes()); } else { inputStream = replicationPackage.createInputStream(); } if (inputStream != null) { req = req.bodyStream(inputStream, ContentType.APPLICATION_OCTET_STREAM); } response = executor.execute(req); } finally { IOUtils.closeQuietly(inputStream); } if (response != null) { Content content = response.returnContent(); if (log.isInfoEnabled()) { log.info("Replication content of type {} for {} delivered: {}", new Object[] { type, Arrays.toString(replicationPackage.getPaths()), content }); } } else { throw new IOException("response is empty"); } }
From source file:com.baifendian.swordfish.common.storm.StormRestUtil.java
/** * kill // www . jav a 2s . c o m */ public static void topologyKill(String topologyId, long waitTime) throws Exception { String res = Request.Post(getTopologyKillUrl(topologyId, waitTime)).execute().returnContent().toString(); TopologyOperationDto topologyOperation = JsonUtil.parseObject(res, TopologyOperationDto.class); if (topologyOperation == null) { throw new Exception("kill not result return!"); } if (!StringUtils.equalsIgnoreCase(topologyOperation.getStatus(), "success")) { String msg = MessageFormat.format("Kill status not equal success: {0}", topologyOperation.getStatus()); throw new Exception(msg); } }
From source file:net.bluemix.newsaggregator.api.AuthenticationServlet.java
private String getAccessTokenFromCodeResponse(String id, String secret, String redirect, String code) { String output = null;/*from ww w .j ava 2 s . com*/ try { configureSSL(); org.apache.http.client.fluent.Request req = Request .Post("https://idaas.ng.bluemix.net/sps/oauth20sp/oauth20/token"); String body = "client_secret=" + secret + "&grant_type=authorization_code" + "&redirect_uri=" + redirect + "&code=" + code + "&client_id=" + id; req.bodyString(body, ContentType.create("application/x-www-form-urlencoded")); org.apache.http.client.fluent.Response res = req.execute(); output = res.returnContent().asString(); output = output.substring(output.indexOf("access_token") + 15, output.indexOf("access_token") + 35); } catch (IOException e) { e.printStackTrace(); } return output; }