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:net.jadler.JadlerStubbingIntegrationTest.java
@Test public void havingEmptyBody() throws Exception { onRequest().havingBodyEqualTo("").havingBody(notNullValue()).havingBody(isEmptyString()).respond() .withStatus(201);//from www .j av a2 s . co m final PostMethod method = new PostMethod("http://localhost:" + port()); method.setRequestEntity(new StringRequestEntity("", null, null)); int status = client.executeMethod(method); assertThat(status, is(201)); }
From source file:com.zimbra.examples.extns.samlprovider.SamlAuthProvider.java
/** * Returns an AuthToken by auth data in SOAP request. * <p/>/* w ww . jav a 2 s . co m*/ * Should never return null. * * @param soapCtxt soap context element * @param engineCtxt soap engine context * @return auth token * @throws AuthTokenException if auth data for the provider is not present * @throws AuthProviderException if auth data for the provider is present but cannot be resolved into a valid AuthToken */ protected AuthToken authToken(Element soapCtxt, Map engineCtxt) throws AuthProviderException, AuthTokenException { if (soapCtxt == null) throw AuthProviderException.NO_AUTH_DATA(); Element authTokenElt; String type; try { authTokenElt = soapCtxt.getElement("authToken"); if (authTokenElt == null) throw AuthProviderException.NO_AUTH_DATA(); type = authTokenElt.getAttribute("type"); } catch (AuthProviderException ape) { throw ape; } catch (ServiceException se) { ZimbraLog.extensions.error(SystemUtil.getStackTrace(se)); throw AuthProviderException.NO_AUTH_DATA(); } if (!"SAML_AUTH_PROVIDER".equals(type)) { throw AuthProviderException.NOT_SUPPORTED(); } String samlAssertionId = authTokenElt.getTextTrim(); if (samlAssertionId == null || "".equals(samlAssertionId)) throw AuthProviderException.NO_AUTH_DATA(); String samlAuthorityUrl = LC.get("saml_authority_url"); if (samlAuthorityUrl == null) throw new AuthTokenException("SAML authority URL has not been specified in localconfig.zml"); HttpClient client = new HttpClient(); PostMethod post = new PostMethod(samlAuthorityUrl); Element samlAssertionReq = getSamlAssertionRequest(samlAssertionId); String samlAssertionReqStr = samlAssertionReq.toString(); if (ZimbraLog.extensions.isDebugEnabled()) { ZimbraLog.extensions.debug("SAML assertion request: " + samlAssertionReqStr); } try { post.setRequestEntity(new StringRequestEntity(samlAssertionReqStr, "text/xml", "utf-8")); client.executeMethod(post); Element samlResp = Element.parseXML(post.getResponseBodyAsStream()); Element soapBody = samlResp.getElement("Body"); Element responseElt = soapBody.getElement("Response"); Element samlAssertionElt = responseElt.getElement("Assertion"); if (samlAssertionElt == null) { throw new AuthTokenException("SAML response does not contain a SAML token"); } return new SamlAuthToken(samlAssertionElt); } catch (AuthTokenException ate) { throw ate; } catch (Exception e) { ZimbraLog.extensions.error(SystemUtil.getStackTrace(e)); throw new AuthTokenException("Exception in executing SAML assertion request", e); } }
From source file:net.jadler.AbstractJadlerStubbingIntegrationTest.java
@Test public void havingBody() throws Exception { onRequest().havingBodyEqualTo("postbody").havingBody(notNullValue()).havingBody(not(isEmptyOrNullString())) .respond().withStatus(201);/* w ww.j a va 2 s . com*/ final PostMethod method = new PostMethod("http://localhost:" + port()); method.setRequestEntity(new StringRequestEntity("postbody", null, null)); int status = client.executeMethod(method); assertThat(status, is(201)); method.releaseConnection(); }
From source file:com.xerox.amazonws.sqs.MessageQueue.java
/** * Sends a message to a specified queue. The message must be between 1 and 256K bytes long. * * @param msg the message to be sent//from w ww .ja v a 2s .com */ public String sendMessage(String msg) throws SQSException { Map<String, String> params = new HashMap<String, String>(); String encodedMsg = enableEncoding ? new String(Base64.encodeBase64(msg.getBytes())) : msg; PostMethod method = new PostMethod(); try { method.setRequestEntity(new StringRequestEntity(encodedMsg, "text/plain", null)); SendMessageResponse response = makeRequest(method, "SendMessage", params, SendMessageResponse.class); return response.getMessageId(); } catch (JAXBException ex) { throw new SQSException("Problem parsing returned message.", ex); } catch (HttpException ex) { throw new SQSException(ex.getMessage(), ex); } catch (IOException ex) { throw new SQSException(ex.getMessage(), ex); } finally { method.releaseConnection(); } }
From source file:com.kodokux.github.api.GithubApiUtil.java
@NotNull private static HttpMethod doREST(@NotNull final GithubAuthData auth, @NotNull final String uri, @Nullable final String requestBody, @NotNull final Collection<Header> headers, @NotNull final HttpVerb verb) throws IOException { HttpClient client = getHttpClient(auth.getBasicAuth(), auth.isUseProxy()); HttpMethod method;//from ww w . jav a 2 s . c om switch (verb) { case POST: method = new PostMethod(uri); if (requestBody != null) { ((PostMethod) method) .setRequestEntity(new StringRequestEntity(requestBody, "application/json", "UTF-8")); } break; case GET: method = new GetMethod(uri); break; case DELETE: method = new DeleteMethod(uri); break; case HEAD: method = new HeadMethod(uri); break; default: throw new IllegalStateException("Wrong HttpVerb: unknown method: " + verb.toString()); } GithubAuthData.TokenAuth tokenAuth = auth.getTokenAuth(); if (tokenAuth != null) { method.addRequestHeader("Authorization", "token " + tokenAuth.getToken()); } for (Header header : headers) { method.addRequestHeader(header); } client.executeMethod(method); return method; }
From source file:it.geosolutions.figis.requester.HTTPUtils.java
/** * PUTs a String to the given URL.//from www . j a v a 2 s. c o m * <BR>Basic auth is used if both username and pw are not null. * * @param url The URL where to connect to. * @param content The content to be sent as a String. * @param contentType The content-type to advert in the PUT. * @param username Basic auth credential. No basic auth if null. * @param pw Basic auth credential. No basic auth if null. * @return The HTTP response as a String if the HTTP response code was 200 (OK). * @throws MalformedURLException * @return the HTTP response or <TT>null</TT> on errors. */ public static String put(String url, String content, String contentType, String username, String pw) { try { return put(url, new StringRequestEntity(content, contentType, null), username, pw); } catch (UnsupportedEncodingException ex) { LOGGER.error("Cannot PUT " + url, ex); return null; } }
From source file:net.mojodna.searchable.solr.SolrIndexer.java
/** * Serialize the Document and hand it to Solr. *//*from ww w. j a v a 2 s. co m*/ @Override protected void save(final Document doc) throws IndexingException { final Element add = new Element("add"); add.addContent(DocumentConverter.convert(doc)); // now do something with the add block try { final XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); final String addString = out.outputString(add); final PostMethod post = new PostMethod(solrPath); post.setRequestEntity(new StringRequestEntity(addString, "text/xml", "UTF-8")); log.debug("Adding:\n" + addString); getHttpClient().executeMethod(post); if (!isBatchMode()) { commit(); } } catch (final IOException e) { throw new IndexingException(e); } }
From source file:eu.eco2clouds.api.bonfire.client.rest.RestClient.java
/** * Performs a POST method against the API * @param url -> This URL is going to be converted to API_URL:BONFIRE_PORT/url * @param payload message sent in the post method * @param type specifies the content type of the request * @return Response object encapsulation all the HTTP information, it returns <code>null</code> if there was an error. *///from w w w .j a va 2 s . c om public static Response executePostMethod(String url, String username, String password, String payload, String type) { Response response = null; try { PostMethod post = new PostMethod(url); // We define the request entity RequestEntity requestEntity = new StringRequestEntity(payload, type, null); post.setRequestEntity(requestEntity); response = executeMethod(post, BONFIRE_XML, username, password, url); } catch (UnsupportedEncodingException exception) { System.out.println("THE PAYLOAD ENCODING IS NOT SUPPORTED"); System.out.println("ERROR: " + exception.getMessage()); System.out.println("ERROR: " + exception.getStackTrace()); } return response; }
From source file:com.uber.jenkins.phabricator.uberalls.UberallsClient.java
public boolean recordCoverage(String sha, CodeCoverageMetrics codeCoverageMetrics) { if (codeCoverageMetrics != null && codeCoverageMetrics.isValid()) { JSONObject params = new JSONObject(); params.put("sha", sha); params.put("branch", branch); params.put("repository", repository); params.put(PACKAGE_COVERAGE_KEY, codeCoverageMetrics.getPackageCoveragePercent()); params.put(FILES_COVERAGE_KEY, codeCoverageMetrics.getFilesCoveragePercent()); params.put(CLASSES_COVERAGE_KEY, codeCoverageMetrics.getClassesCoveragePercent()); params.put(METHOD_COVERAGE_KEY, codeCoverageMetrics.getMethodCoveragePercent()); params.put(LINE_COVERAGE_KEY, codeCoverageMetrics.getLineCoveragePercent()); params.put(CONDITIONAL_COVERAGE_KEY, codeCoverageMetrics.getConditionalCoveragePercent()); try {//from ww w .j av a 2 s . c o m HttpClient client = getClient(); PostMethod request = new PostMethod(getBuilder().build().toString()); request.addRequestHeader("Content-Type", "application/json"); StringRequestEntity requestEntity = new StringRequestEntity(params.toString(), ContentType.APPLICATION_JSON.toString(), "UTF-8"); request.setRequestEntity(requestEntity); int statusCode = client.executeMethod(request); if (statusCode != HttpStatus.SC_OK) { logger.info(TAG, "Call failed: " + request.getStatusLine()); return false; } return true; } catch (URISyntaxException e) { e.printStackTrace(); } catch (HttpResponseException e) { // e.g. 404, pass logger.info(TAG, "HTTP Response error recording metrics: " + e); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return false; }
From source file:net.jadler.JadlerMockingIntegrationTest.java
@Test public void havingISOBody() throws Exception { final PostMethod method = new PostMethod("http://localhost:" + port()); method.setRequestEntity(//from w w w . j av a2 s. c om new StringRequestEntity(STRING_WITH_DIACRITICS, "text/plain", ISO_8859_2_CHARSET.name())); client.executeMethod(method); verifyThatRequest().havingBodyEqualTo(STRING_WITH_DIACRITICS) .havingRawBodyEqualTo(ISO_8859_2_REPRESENTATION).receivedOnce(); }