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.AbstractJadlerStubbingIntegrationTest.java
@Test public void respondUsingResponder() throws IOException { onRequest().havingMethodEqualTo("POST").respondUsing(new Responder() { @Override//from w w w . j a v a 2 s . com public StubResponse nextResponse(final Request request) { return StubResponse.builder().status(201) .header("Content-Type", "text/plain; charset=" + request.getEncoding().name()) .body(request.getBodyAsBytes()).build(); } }); final PostMethod method = new PostMethod("http://localhost:" + port()); method.setRequestEntity(new StringRequestEntity(STRING_WITH_DIACRITICS, UTF_8_TYPE, null)); final int status = client.executeMethod(method); assertThat(status, is(201)); assertThat(method.getResponseBodyAsString(), is(STRING_WITH_DIACRITICS)); method.releaseConnection(); }
From source file:eu.learnpad.core.impl.or.XwikiBridgeInterfaceRestResource.java
@Override public void updateSimulationScore(String modelSetId, String simulationSessionId, String processArtifactId, Long timestamp, String userId, SimulationScoresMap scoreMap) throws LpRestException { HttpClient httpClient = this.getClient(); String uri = String.format("%s/learnpad/or/bridge/%s/simulationscore", DefaultRestResource.REST_URI, modelSetId);//from w ww .ja va2 s. c o m PostMethod postMethod = new PostMethod(uri); postMethod.addRequestHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML); String contentType = "application/xml"; NameValuePair[] queryString = new NameValuePair[4]; queryString[0] = new NameValuePair("simulationsessionid", simulationSessionId); queryString[1] = new NameValuePair("processartifactid", processArtifactId); queryString[2] = new NameValuePair("timestamp", timestamp.toString()); queryString[3] = new NameValuePair("userid", userId); postMethod.setQueryString(queryString); try { Writer scoreMapWriter = new StringWriter(); JAXBContext jc = JAXBContext.newInstance(SimulationScoresMap.class); jc.createMarshaller().marshal(scoreMap, scoreMapWriter); RequestEntity requestEntity = new StringRequestEntity(scoreMapWriter.toString(), contentType, "UTF-8"); postMethod.setRequestEntity(requestEntity); httpClient.executeMethod(postMethod); } catch (IOException | JAXBException e) { throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause()); } }
From source file:com.inbravo.scribe.rest.service.crm.ZDRESTCRMService.java
@Override public final ScribeCommandObject updateObject(final ScribeCommandObject cADCommandObject) throws Exception { logger.debug("----Inside updateObject"); PutMethod putMethod = null;/* ww w. j a v a 2 s.c o m*/ try { String serviceURL = null; String serviceProtocol = null; String userId = null; String password = null; String sessionId = null; String crmPort = "80"; /* Check if crm user info is present in request */ if (cADCommandObject.getCrmUserId() != null) { /* Get agent from session manager */ final ScribeCacheObject agent = zDCRMSessionManager .getCrmUserIdWithCRMSessionInformation(cADCommandObject.getCrmUserId()); /* Get CRM information from agent */ serviceURL = agent.getScribeMetaObject().getCrmServiceURL(); serviceProtocol = agent.getScribeMetaObject().getCrmServiceProtocol(); userId = agent.getScribeMetaObject().getCrmUserId(); password = agent.getScribeMetaObject().getCrmPassword(); sessionId = agent.getScribeMetaObject().getCrmSessionId(); crmPort = agent.getScribeMetaObject().getCrmPort(); } String crmObjectId = null; /* Check if XML content in request, is not null */ if (cADCommandObject.getObject() != null && cADCommandObject.getObject().length == 1) { /* Get Id of CRM object */ crmObjectId = ZDCRMMessageFormatUtils.getNodeValue("ID", cADCommandObject.getObject()[0]); if (crmObjectId == null) { /* Inform user about invalid request */ throw new ScribeException( ScribeResponseCodes._1008 + "CRM object id is not present in request"); } } else { /* Inform user about invalid request */ throw new ScribeException( ScribeResponseCodes._1008 + "CRM object information is not present in request"); } /* Create Zen desk URL */ final String zenDeskURL = serviceProtocol + "://" + serviceURL + "/" + cADCommandObject.getObjectType() + "s/" + crmObjectId + ".xml"; logger.debug("----Inside updateObject zenDeskURL: " + zenDeskURL); /* Instantiate put method */ putMethod = new PutMethod(zenDeskURL); /* Set request content type */ putMethod.addRequestHeader("Content-Type", "application/xml"); putMethod.addRequestHeader("accept", "application/xml"); /* Cookie is required to be set for session management */ putMethod.addRequestHeader("Cookie", sessionId); /* Add request entity */ final RequestEntity entity = new StringRequestEntity( ZDCRMMessageFormatUtils.getCreateRequestXML(cADCommandObject), null, null); putMethod.setRequestEntity(entity); final HttpClient httpclient = new HttpClient(); /* Set credentials */ httpclient.getState().setCredentials(new AuthScope(serviceURL, validateCrmPort(crmPort)), new UsernamePasswordCredentials(userId, password)); /* Execute method */ int result = httpclient.executeMethod(putMethod); logger.debug("----Inside updateObject response code: " + result + " & body: " + putMethod.getResponseBodyAsString()); /* Check if object is updated */ if (result == HttpStatus.SC_OK || result == HttpStatus.SC_CREATED) { /* Return the original object */ return cADCommandObject; } else if (result == HttpStatus.SC_BAD_REQUEST || result == HttpStatus.SC_METHOD_NOT_ALLOWED || result == HttpStatus.SC_NOT_ACCEPTABLE) { throw new ScribeException(ScribeResponseCodes._1003 + "Invalid request : " + ZDCRMMessageFormatUtils.getErrorFromResponse(putMethod.getResponseBodyAsStream())); } else if (result == HttpStatus.SC_UNAUTHORIZED) { throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zendesk CRM"); } else if (result == HttpStatus.SC_NOT_FOUND) { throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zendesk CRM"); } else if (result == HttpStatus.SC_MOVED_TEMPORARILY) { throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zendesk CRM : Seems like Zendesk Service URL/Protocol is not correct"); } } catch (final ScribeException exception) { throw exception; } catch (final ParserConfigurationException exception) { throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid XML from Zendesk CRM", exception); } catch (final SAXException exception) { throw new ScribeException(ScribeResponseCodes._1020 + "Recieved an invalid XML from Zendesk CRM", exception); } catch (final IOException exception) { throw new ScribeException( ScribeResponseCodes._1020 + "Communication error while communicating with Zendesk CRM", exception); } finally { /* Release connection socket */ if (putMethod != null) { putMethod.releaseConnection(); } } return cADCommandObject; }
From source file:com.cubeia.backoffice.wallet.client.WalletServiceClientHTTP.java
@Override public TransactionQueryResult listTransactions(ListTransactionsRequest request) { String uri = baseUrl + TRANSACTIONS; PutMethod method = new PutMethod(uri); try {//from w ww .j a v a 2 s .co m String data = serialize(request); method.setRequestEntity(new StringRequestEntity(data, MIME_TYPE_JSON, DEFAULT_CHAR_ENCODING)); // Execute the HTTP Call int statusCode = getClient().executeMethod(method); if (statusCode == HttpStatus.SC_NOT_FOUND) { return null; } if (statusCode == HttpStatus.SC_OK) { InputStream body = method.getResponseBodyAsStream(); return parseJson(body, TransactionQueryResult.class); } else { throw new RuntimeException( "Failed to list transactions, RESPONSE CODE: " + statusCode + " url: " + uri); } } catch (Exception e) { throw new RuntimeException("Failed listing transactions via url " + uri, e); } finally { method.releaseConnection(); } }
From source file:com.xmlcalabash.library.ApacheHttpRequest.java
private void doPutOrPost(EntityEnclosingMethod method, XdmNode body) { // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); for (Header header : headers) { method.addRequestHeader(header); }/*from ww w . j a v a 2 s . co m*/ contentType = body.getAttributeValue(_content_type); if (contentType == null) { throw new XProcException("Content-type on c:body is required."); } // FIXME: This sucks rocks. I want to write the data to be posted, not provide some way to read it String postContent = null; try { if (xmlContentType(contentType)) { Serializer serializer = makeSerializer(); Vector<XdmNode> content = new Vector<XdmNode>(); XdmSequenceIterator iter = body.axisIterator(Axis.CHILD); while (iter.hasNext()) { XdmNode node = (XdmNode) iter.next(); content.add(node); } // FIXME: set serializer properties appropriately! StringWriter writer = new StringWriter(); serializer.setOutputWriter(writer); S9apiUtils.serialize(runtime, content, serializer); writer.close(); postContent = writer.toString(); } else { StringWriter writer = new StringWriter(); XdmSequenceIterator iter = body.axisIterator(Axis.CHILD); while (iter.hasNext()) { XdmNode node = (XdmNode) iter.next(); writer.write(node.getStringValue()); } writer.close(); postContent = writer.toString(); } StringRequestEntity requestEntity = new StringRequestEntity(postContent, contentType, "UTF-8"); method.setRequestEntity(requestEntity); } catch (IOException ioe) { throw new XProcException(ioe); } catch (SaxonApiException sae) { throw new XProcException(sae); } }
From source file:com.cubeia.backoffice.users.client.UserServiceClientHTTP.java
@Override public void updatePassword(Long userId, String newPassword) { String resource = String.format(baseUrl + SET_PASSWORD, userId); PutMethod method = new PutMethod(resource); try {/*w ww . j av a 2s.c o m*/ ChangeUserPasswordRequest request = new ChangeUserPasswordRequest(); request.setPassword(newPassword); String data = serialize(request); method.setRequestEntity(new StringRequestEntity(data, "application/json", "UTF-8")); // Execute the HTTP Call int statusCode = getClient().executeMethod(method); if (statusCode == HttpStatus.SC_NOT_FOUND) { return; } assertResponseCodeOK(method, statusCode); } catch (Exception e) { throw new RuntimeException(e); } finally { method.releaseConnection(); } }
From source file:com.apifest.oauth20.tests.OAuth20BasicTest.java
public String registerNewScope(String scope, String description, int ccExpiresIn, int passExpiresIn) { PostMethod post = new PostMethod(baseOAuth20Uri + SCOPE_ENDPOINT); String response = null;//from ww w.j ava 2 s. c o m try { JSONObject json = new JSONObject(); json.put("scope", scope); json.put("description", description); json.put("cc_expires_in", ccExpiresIn); json.put("pass_expires_in", passExpiresIn); String requestBody = json.toString(); RequestEntity requestEntity = new StringRequestEntity(requestBody, "application/json", "UTF-8"); post.setRequestHeader(HttpHeaders.CONTENT_TYPE, "application/json"); post.setRequestEntity(requestEntity); response = readResponse(post); log.info(response); } catch (IOException e) { log.error("cannot register new scope", e); } catch (JSONException e) { log.error("cannot register new scope", e); } return response; }
From source file:io.fabric8.gateway.servlet.ProxyServlet.java
/** * Sets up the given {@link PostMethod} to send the same standard * data as was sent in the given {@link javax.servlet.http.HttpServletRequest} * * @param entityEnclosingMethod The {@link EntityEnclosingMethod} that we are * configuring to send a standard request * @param httpServletRequest The {@link javax.servlet.http.HttpServletRequest} that contains * the data to be sent via the {@link EntityEnclosingMethod} */// ww w. j a v a 2 s .co m @SuppressWarnings("unchecked") private void handleEntity(EntityEnclosingMethod entityEnclosingMethod, HttpServletRequest httpServletRequest) throws IOException { // Get the client POST data as a Map Map<String, String[]> mapPostParameters = (Map<String, String[]>) httpServletRequest.getParameterMap(); // Create a List to hold the NameValuePairs to be passed to the PostMethod List<NameValuePair> listNameValuePairs = new ArrayList<NameValuePair>(); // Iterate the parameter names for (String stringParameterName : mapPostParameters.keySet()) { // Iterate the values for each parameter name String[] stringArrayParameterValues = mapPostParameters.get(stringParameterName); for (String stringParamterValue : stringArrayParameterValues) { // Create a NameValuePair and store in list NameValuePair nameValuePair = new NameValuePair(stringParameterName, stringParamterValue); listNameValuePairs.add(nameValuePair); } } RequestEntity entity = null; String contentType = httpServletRequest.getContentType(); if (contentType != null) { contentType = contentType.toLowerCase(); if (contentType.contains("json") || contentType.contains("xml") || contentType.contains("application") || contentType.contains("text")) { String body = IOHelpers.readFully(httpServletRequest.getReader()); entity = new StringRequestEntity(body, contentType, httpServletRequest.getCharacterEncoding()); entityEnclosingMethod.setRequestEntity(entity); } } NameValuePair[] parameters = listNameValuePairs.toArray(new NameValuePair[] {}); if (entity != null) { // TODO add as URL parameters? //postMethodProxyRequest.addParameters(parameters); } else { // Set the proxy request POST data if (entityEnclosingMethod instanceof PostMethod) { ((PostMethod) entityEnclosingMethod).setRequestBody(parameters); } } }
From source file:eu.eco2clouds.scheduler.accounting.client.AccountingClientHC.java
private String putMethod(String url, String payload, String bonfireUserId, String bonfireGroupId, Boolean exception) {//from w ww. j ava 2s . com // Create an instance of HttpClient. HttpClient client = getHttpClient(); logger.debug("Connecting to: " + url); // Create a method instance. PutMethod method = new PutMethod(url); setHeaders(method, bonfireGroupId, bonfireUserId); //method.addRequestHeader("Content-Type", SchedulerDictionary.CONTENT_TYPE_ECO2CLOUDS_XML); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); String response = ""; try { // We set the payload StringRequestEntity payloadEntity = new StringRequestEntity(payload, SchedulerDictionary.CONTENT_TYPE_ECO2CLOUDS_XML, "UTF-8"); method.setRequestEntity(payloadEntity); // Execute the method. int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { //TODO test for this case... logger.warn("Get host information of testbeds: " + url + " failed: " + method.getStatusLine()); } else { // Read the response body. byte[] responseBody = method.getResponseBody(); response = new String(responseBody); } } catch (HttpException e) { logger.warn("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); exception = true; } catch (IOException e) { logger.warn("Fatal transport error: " + e.getMessage()); e.printStackTrace(); exception = true; } finally { // Release the connection. method.releaseConnection(); } return response; }
From source file:com.cubeia.backoffice.users.client.UserServiceClientHTTP.java
@Override public CreateUserResponse createUser(CreateUserRequest request) { PostMethod method = new PostMethod(baseUrl + CREATE_USER); try {/*from w ww . j ava2 s .co m*/ String data = serialize(request); method.setRequestEntity(new StringRequestEntity(data, "application/json", "UTF-8")); // Execute the HTTP Call int statusCode = getClient().executeMethod(method); if (statusCode == HttpStatus.SC_NOT_FOUND) { return null; } if (statusCode == HttpStatus.SC_OK) { InputStream body = method.getResponseBodyAsStream(); return parseJson(body, CreateUserResponse.class); } else { throw new RuntimeException("Failed to create user, RESPONSE CODE: " + statusCode); } } catch (Exception e) { throw new RuntimeException(e); } finally { method.releaseConnection(); } }