List of usage examples for org.apache.commons.httpclient.methods StringRequestEntity StringRequestEntity
public StringRequestEntity(String paramString1, String paramString2, String paramString3) throws UnsupportedEncodingException
From source file:edu.internet2.middleware.grouper.changeLog.esb2.consumer.EsbHttpPublisher.java
@Override public boolean dispatchEvent(String eventJsonString, String consumerName) { // TODO Auto-generated method stub String urlString = GrouperLoaderConfig .getPropertyString("changeLog.consumer." + consumerName + ".publisher.url"); String username = GrouperLoaderConfig .getPropertyString("changeLog.consumer." + consumerName + ".publisher.username", ""); String password = GrouperLoaderConfig .getPropertyString("changeLog.consumer." + consumerName + ".publisher.password", ""); if (LOG.isDebugEnabled()) { LOG.debug("Consumer name: " + consumerName + " sending " + GrouperUtil.indent(eventJsonString, false) + " to " + urlString); }// ww w . j a v a 2 s .c om int retries = GrouperLoaderConfig .getPropertyInt("changeLog.consumer." + consumerName + ".publisher.retries", 0); int timeout = GrouperLoaderConfig .getPropertyInt("changeLog.consumer." + consumerName + ".publisher.timeout", 60000); PostMethod post = new PostMethod(urlString); post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(retries, false)); post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, new Integer(timeout)); post.setRequestHeader("Content-Type", "application/json; charset=utf-8"); RequestEntity requestEntity; try { requestEntity = new StringRequestEntity(eventJsonString, "application/json", "utf-8"); post.setRequestEntity(requestEntity); HttpClient httpClient = new HttpClient(); if (!(username.equals(""))) { if (LOG.isDebugEnabled()) { LOG.debug("Authenticating using basic auth"); } URL url = new URL(urlString); httpClient.getState().setCredentials(new AuthScope(null, url.getPort(), null), new UsernamePasswordCredentials(username, password)); httpClient.getParams().setAuthenticationPreemptive(true); post.setDoAuthentication(true); } int statusCode = httpClient.executeMethod(post); if (statusCode == 200) { if (LOG.isDebugEnabled()) { LOG.debug("Status code 200 recieved, event sent OK"); } return true; } else { if (LOG.isDebugEnabled()) { LOG.debug("Status code " + statusCode + " recieved, event send failed"); } return false; } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; }
From source file:com.kylinolap.jdbc.stub.KylinClient.java
@Override public void connect() throws ConnectionException { PostMethod post = new PostMethod(conn.getConnectUrl()); HttpClient httpClient = new HttpClient(); if (conn.getConnectUrl().toLowerCase().startsWith("https://")) { registerSsl();// w w w. j av a2 s . c o m } addPostHeaders(post); try { StringRequestEntity requestEntity = new StringRequestEntity("{}", "application/json", "UTF-8"); post.setRequestEntity(requestEntity); httpClient.executeMethod(post); if (post.getStatusCode() != 200 && post.getStatusCode() != 201) { logger.error("Authentication Failed with error code " + post.getStatusCode() + " and message:\n" + post.getResponseBodyAsString()); throw new ConnectionException("Authentication Failed."); } } catch (HttpException e) { logger.error(e.getLocalizedMessage(), e); throw new ConnectionException(e.getLocalizedMessage()); } catch (IOException e) { logger.error(e.getLocalizedMessage(), e); throw new ConnectionException(e.getLocalizedMessage()); } }
From source file:com.boundary.sdk.event.notification.WebhookRouteBuilderTest.java
@Test public void testNotification() throws InterruptedException, IOException { String body = readFile(NOTIFICATION_JSON, Charset.defaultCharset()); out.setExpectedMessageCount(1);//from ww w . j a va 2s .co m // Get the url from the sprint DSL file by // 1) Getting the context // 2) Getting the registry // 3) Lookup the bean // 4) Call method to get url // 5) Strip out component name, "jetty:" CamelContext context = out.getCamelContext(); Registry registry = context.getRegistry(); WebHookRouteBuilder builder = (WebHookRouteBuilder) registry.lookupByName("webhook-route-builder"); assertNotNull("builder is null", builder); String url = null; url = builder.getFromUri(); url = url.replaceFirst("jetty:", ""); LOG.debug("url {}", url); // Send an HTTP request with the JSON paylod that is sent // from a Boundary Event Notification HttpClient httpclient = new HttpClient(); PostMethod httppost = new PostMethod(url); Header contentHeader = new Header("Content-Type", "application/json"); httppost.setRequestHeader(contentHeader); StringRequestEntity reqEntity = new StringRequestEntity(body, null, null); httppost.setRequestEntity(reqEntity); // Check our reponse status int status = httpclient.executeMethod(httppost); assertEquals("Received wrong response status", 200, status); // Assert the mock end point out.assertIsSatisfied(); // Get List<Exchange> exchanges = out.getExchanges(); LOG.debug("EXCHANGE COUNT: " + exchanges.size()); for (Exchange exchange : exchanges) { Message message = exchange.getIn(); Object o = message.getBody(); LOG.debug("class: " + o.getClass().toString()); Notification notif = message.getBody(Notification.class); validateNotification(notif); } }
From source file:com.temenos.interaction.commands.webhook.WebhookCommand.java
/** * @precondition url has been supplied//from w w w .j ava2 s.co m * @postcondition Result.Success if {@link InteractionContext#getResource()} is successfully POSTed to url */ @SuppressWarnings("unchecked") @Override public Result execute(InteractionContext ctx) { if (url != null && url.length() > 0) { Map<String, Object> properties = null; try { OEntity oentity = ((EntityResource<OEntity>) ctx.getResource()).getEntity(); properties = transform(oentity); } catch (ClassCastException cce) { if (LOGGER.isWarnEnabled()) { LOGGER.warn("Failed to cast the OEntity.", cce); } Entity entity = ((EntityResource<Entity>) ctx.getResource()).getEntity(); properties = transform(entity); } String formData = getFormData(properties); try { LOGGER.info("POST " + url + " [" + formData + "]"); HttpClient client = new HttpClient(); PostMethod postMethod = new PostMethod(url); postMethod.setRequestEntity( new StringRequestEntity(formData, "application/x-www-form-urlencoded", "UTF-8")); client.executeMethod(postMethod); LOGGER.info("Status [" + postMethod.getStatusCode() + "]"); } catch (Exception e) { LOGGER.error("Error POST " + url + " [" + formData + "]", e); return Result.FAILURE; } } else { LOGGER.warn("DISABLED - no url supplied"); } return Result.SUCCESS; }
From source file:net.neurowork.cenatic.centraldir.workers.XMLPusher.java
private void pushOrganization(RestUrlManager restUrl, String token) { HttpClient httpclient = XMLRestWorker.getHttpClient(); PostMethod post = new PostMethod(restUrl.getPushOrganizationUrl()); NameValuePair tokenParam = new NameValuePair("token", token); NameValuePair[] params = new NameValuePair[] { tokenParam }; post.addRequestHeader("Accept", "application/xml"); post.setQueryString(params);/*from w ww. j a v a 2s . c o m*/ String content = XmlPushCreator.getInstance().getPushXml(organizacion); try { RequestEntity entity = new StringRequestEntity(content, PostMethod.FORM_URL_ENCODED_CONTENT_TYPE, null); post.setRequestEntity(entity); int result = httpclient.executeMethod(post); logger.info("Response status code: " + result); logger.info("Response body: "); logger.info(post.getResponseBodyAsString()); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage()); } catch (HttpException e) { logger.error(e.getMessage()); } catch (IOException e) { logger.error(e.getMessage()); } finally { post.releaseConnection(); } }
From source file:com.avego.cloudinary.Cloudinary.java
private String postJsonToCloudinary(PostMethod post, StringBuilder payload) throws CloudinaryException { HttpClient client = new HttpClient(); StringRequestEntity body;/*from www. ja v a2 s .c o m*/ try { body = new StringRequestEntity(payload.toString(), "application/json", "UTF-8"); } catch (UnsupportedEncodingException e) { throw new CloudinaryException("JSON is not supported by Implementation of String Request Entity.", e); } post.setRequestEntity(body); int status; try { status = client.executeMethod(post); } catch (IOException e) { throw new CloudinaryException("A HTTP Exception Occurred while attempting to POST JSON to CLoudinary.", e); } String response = null; try { response = post.getResponseBodyAsString(); } catch (IOException e) { throw new CloudinaryException("Failed to Retrieve response from POST Method.", e); } if (status != 200) { throw new CloudinaryException("Cloudinary Operation was Unsuccessful. Response was: " + response); } LOGGER.info("POST was successfully sent to Cloudinary, response was: " + response); return response; }
From source file:com.owncloud.android.lib.resources.files.UpdateMetadataOperation.java
/** * @param client Client object//ww w.j av a2 s. c o m */ @Override protected RemoteOperationResult run(OwnCloudClient client) { PutMethod putMethod = null; RemoteOperationResult result; try { // remote request putMethod = new PutMethod(client.getBaseUri() + METADATA_URL + fileId); putMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE); putMethod.addRequestHeader(CONTENT_TYPE, FORM_URLENCODED); NameValuePair[] putParams = new NameValuePair[2]; putParams[0] = new NameValuePair(TOKEN, token); putParams[1] = new NameValuePair(FORMAT, "json"); putMethod.setQueryString(putParams); StringRequestEntity data = new StringRequestEntity("metaData=" + encryptedMetadataJson, "application/json", "UTF-8"); putMethod.setRequestEntity(data); int status = client.executeMethod(putMethod, SYNC_READ_TIMEOUT, SYNC_CONNECTION_TIMEOUT); if (status == HttpStatus.SC_OK) { String response = putMethod.getResponseBodyAsString(); // Parse the response JSONObject respJSON = new JSONObject(response); String metadata = (String) respJSON.getJSONObject(NODE_OCS).getJSONObject(NODE_DATA) .get(NODE_META_DATA); result = new RemoteOperationResult(true, putMethod); ArrayList<Object> keys = new ArrayList<>(); keys.add(metadata); result.setData(keys); } else { result = new RemoteOperationResult(false, putMethod); client.exhaustResponse(putMethod.getResponseBodyAsStream()); } } catch (Exception e) { result = new RemoteOperationResult(e); Log_OC.e(TAG, "Storing of metadata for folder " + fileId + " failed: " + result.getLogMessage(), result.getException()); } finally { if (putMethod != null) putMethod.releaseConnection(); } return result; }
From source file:com.honnix.yaacs.adapter.http.TestACHttpServer.java
private Map<String, String> login() throws HttpException, IOException { StringBuilder sb = new StringBuilder(HOST).append(ACHttpPropertiesConstant.HTTP_LISTENING_PORT) .append(ACHttpPropertiesConstant.HTTP_SESSION_CONTROL_URL); postMethod = new PostMethod(sb.toString()); postMethod.setRequestHeader(CONTENT_TYPE_KEY, CONTENT_TYPE); StringRequestEntity requestEntity = new StringRequestEntity( ACHttpBodyUtil.buildLoginRequestBody(USER_ID, PASSWORD), null, ACHttpPropertiesConstant.HTTP_CHARSET); postMethod.setRequestEntity(requestEntity); int statusCode = client.executeMethod(postMethod); assertEquals(SHOULD_BE_OK, HttpStatus.SC_OK, statusCode); return ACHttpBodyUtil.buildParameterMap(postMethod.getResponseBodyAsStream(), ACHttpPropertiesConstant.HTTP_CHARSET); }
From source file:net.mojodna.searchable.solr.SolrIndexer.java
@Override protected void delete(final Serializable key) throws IndexingException { final Element delete = new Element("delete").addContent( new Element("query").addContent(IndexSupport.COMPOUND_ID_FIELD_NAME + ":" + key.toString())); // now do something with the delete block try {/*from w w w . j ava2s. c o m*/ final XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); final String deleteString = out.outputString(delete); final PostMethod post = new PostMethod(solrPath); post.setRequestEntity(new StringRequestEntity(deleteString, "text/xml", "UTF-8")); log.debug("Deleting:\n" + deleteString); getHttpClient().executeMethod(post); if (!isBatchMode()) { commit(); } } catch (final IOException e) { throw new IndexingException(e); } }
From source file:edu.unc.lib.dl.admin.controller.AbstractSwordController.java
public String updateDatastream(String pid, String datastream, HttpServletRequest request, HttpServletResponse response) {//from w w w . j av a2s. c o m String responseString = null; String dataUrl = swordUrl + "object/" + pid; if (datastream != null) dataUrl += "/" + datastream; Abdera abdera = new Abdera(); Entry entry = abdera.newEntry(); Parser parser = abdera.getParser(); Document<FOMExtensibleElement> doc; HttpClient client; PutMethod method; ParserOptions parserOptions = parser.getDefaultParserOptions(); parserOptions.setCharset(request.getCharacterEncoding()); try { doc = parser.parse(request.getInputStream(), parserOptions); entry.addExtension(doc.getRoot()); client = HttpClientUtil.getAuthenticatedClient(dataUrl, swordUsername, swordPassword); client.getParams().setAuthenticationPreemptive(true); method = new PutMethod(dataUrl); // Pass the users groups along with the request method.addRequestHeader(HttpClientUtil.FORWARDED_GROUPS_HEADER, GroupsThreadStore.getGroupString()); Header header = new Header("Content-Type", "application/atom+xml"); method.setRequestHeader(header); StringWriter stringWriter = new StringWriter(2048); StringRequestEntity requestEntity; entry.writeTo(stringWriter); requestEntity = new StringRequestEntity(stringWriter.toString(), "application/atom+xml", "UTF-8"); method.setRequestEntity(requestEntity); } catch (UnsupportedEncodingException e) { log.error("Encoding not supported", e); return null; } catch (IOException e) { log.error("IOException while writing entry", e); return null; } try { client.executeMethod(method); response.setStatus(method.getStatusCode()); if (method.getStatusCode() == HttpStatus.SC_NO_CONTENT) { // success return ""; } else if (method.getStatusCode() >= 400 && method.getStatusCode() <= 500) { if (method.getStatusCode() == 500) log.warn("Failed to upload " + datastream + " " + method.getURI().getURI()); // probably a validation problem responseString = method.getResponseBodyAsString(); return responseString; } else { response.setStatus(500); throw new Exception("Failure to update fedora content due to response of: " + method.getStatusLine().toString() + "\nPath was: " + method.getURI().getURI()); } } catch (Exception e) { log.error("Error while attempting to stream Fedora content for " + pid, e); } finally { if (method != null) method.releaseConnection(); } return responseString; }