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:eu.learnpad.core.impl.cw.XwikiCoreFacadeRestResource.java
@Override public Entities analyseText(String modelSetId, String contextArtifactId, String userId, String title, String text) throws LpRestException { HttpClient httpClient = this.getClient(); String uri = String.format("%s/learnpad/cw/corefacade/semantic/%s/analysetext", DefaultRestResource.REST_URI, modelSetId); PostMethod postMethod = new PostMethod(uri); postMethod.addRequestHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML); NameValuePair[] queryString = new NameValuePair[4]; queryString[0] = new NameValuePair("modelsetid", modelSetId); queryString[1] = new NameValuePair("contextArtifactId", contextArtifactId); queryString[2] = new NameValuePair("userid", userId); queryString[3] = new NameValuePair("title", title); postMethod.setQueryString(queryString); RequestEntity requestEntity;/*from w ww. j a v a 2 s.com*/ InputStream entitiesAsStream = null; try { requestEntity = new StringRequestEntity(text, MediaType.APPLICATION_XML, "UTF-8"); postMethod.setRequestEntity(requestEntity); httpClient.executeMethod(postMethod); entitiesAsStream = postMethod.getResponseBodyAsStream(); } catch (IOException e) { throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause()); } Entities entities = null; try { JAXBContext jc = JAXBContext.newInstance(Entities.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); entities = (Entities) unmarshaller.unmarshal(entitiesAsStream); } catch (JAXBException e) { throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause()); } return entities; }
From source file:com.bluexml.side.framework.alfresco.webscriptExtension.SiteScriptExtension.java
/** * Creates POST method with passed in body and content type * * @param url URL for request// w w w . java 2 s . c o m * @param body body of request * @param contentType content type of request * @return POST method * @throws java.io.UnsupportedEncodingException * */ private PostMethod createPostMethod(String url, String body, String contentType) throws UnsupportedEncodingException { PostMethod postMethod = new PostMethod(url); postMethod.setRequestHeader(HEADER_CONTENT_TYPE, contentType); postMethod.setRequestEntity(new StringRequestEntity(body, CONTENT_TYPE_TEXT_PLAIN, UTF_8)); return postMethod; }
From source file:com.mirth.connect.connectors.http.HttpMessageDispatcher.java
private HttpMethod buildHttpRequest(String address, MessageObject mo) throws Exception { String method = connector.getDispatcherMethod(); String content = replacer.replaceValues(connector.getDispatcherContent(), mo); String contentType = connector.getDispatcherContentType(); String charset = connector.getDispatcherCharset(); boolean isMultipart = connector.isDispatcherMultipart(); Map<String, String> headers = replacer.replaceValuesInMap(connector.getDispatcherHeaders(), mo); Map<String, String> parameters = replacer.replaceValuesInMap(connector.getDispatcherParameters(), mo); HttpMethod httpMethod = null;/*from w w w . j ava 2s.c om*/ // populate the query parameters NameValuePair[] queryParameters = new NameValuePair[parameters.size()]; int index = 0; for (Entry<String, String> parameterEntry : parameters.entrySet()) { queryParameters[index] = new NameValuePair(parameterEntry.getKey(), parameterEntry.getValue()); index++; logger.debug("setting query parameter: [" + parameterEntry.getKey() + ", " + parameterEntry.getValue() + "]"); } // create the method if ("GET".equalsIgnoreCase(method)) { httpMethod = new GetMethod(address); httpMethod.setQueryString(queryParameters); } else if ("POST".equalsIgnoreCase(method)) { PostMethod postMethod = new PostMethod(address); if (isMultipart) { logger.debug("setting multipart file content"); File tempFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp"); FileUtils.writeStringToFile(tempFile, content, charset); Part[] parts = new Part[] { new FilePart(tempFile.getName(), tempFile, contentType, charset) }; postMethod.setQueryString(queryParameters); postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams())); } else if (StringUtils.equals(contentType, "application/x-www-form-urlencoded")) { postMethod.setRequestBody(queryParameters); } else { postMethod.setQueryString(queryParameters); postMethod.setRequestEntity(new StringRequestEntity(content, contentType, charset)); } httpMethod = postMethod; } else if ("PUT".equalsIgnoreCase(method)) { PutMethod putMethod = new PutMethod(address); putMethod.setRequestEntity(new StringRequestEntity(content, contentType, charset)); putMethod.setQueryString(queryParameters); httpMethod = putMethod; } else if ("DELETE".equalsIgnoreCase(method)) { httpMethod = new DeleteMethod(address); httpMethod.setQueryString(queryParameters); } // set the headers for (Entry<String, String> headerEntry : headers.entrySet()) { httpMethod.setRequestHeader(new Header(headerEntry.getKey(), headerEntry.getValue())); logger.debug("setting method header: [" + headerEntry.getKey() + ", " + headerEntry.getValue() + "]"); } return httpMethod; }
From source file:com.ning.http.client.providers.apache.TestableApacheAsyncHttpProvider.java
/** * This one we can get into/*from w w w .j a va2 s . c o m*/ */ protected HttpMethodBase getHttpMethodBase(HttpClient client, Request request) throws IOException { String methodName = request.getMethod(); HttpMethodBase method; if (methodName.equalsIgnoreCase("POST") || methodName.equalsIgnoreCase("PUT")) { EntityEnclosingMethod post = methodName.equalsIgnoreCase("POST") ? new PostMethod(request.getUrl()) : new PutMethod(request.getUrl()); String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding(); post.getParams().setContentCharset("ISO-8859-1"); if (request.getByteData() != null) { post.setRequestEntity(new ByteArrayRequestEntity(request.getByteData())); post.setRequestHeader("Content-Length", String.valueOf(request.getByteData().length)); } else if (request.getStringData() != null) { post.setRequestEntity(new StringRequestEntity(request.getStringData(), "text/xml", bodyCharset)); post.setRequestHeader("Content-Length", String.valueOf(request.getStringData().getBytes(bodyCharset).length)); } else if (request.getStreamData() != null) { InputStreamRequestEntity r = new InputStreamRequestEntity(request.getStreamData()); post.setRequestEntity(r); post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength())); } else if (request.getParams() != null) { StringBuilder sb = new StringBuilder(); for (final Map.Entry<String, List<String>> paramEntry : request.getParams()) { final String key = paramEntry.getKey(); for (final String value : paramEntry.getValue()) { if (sb.length() > 0) { sb.append("&"); } UTF8UrlEncoder.appendEncoded(sb, key); sb.append("="); UTF8UrlEncoder.appendEncoded(sb, value); } } post.setRequestHeader("Content-Length", String.valueOf(sb.length())); post.setRequestEntity(new StringRequestEntity(sb.toString(), "text/xml", "ISO-8859-1")); if (!request.getHeaders().containsKey("Content-Type")) { post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); } } else if (request.getParts() != null) { MultipartRequestEntity mre = createMultipartRequestEntity(bodyCharset, request.getParts(), post.getParams()); post.setRequestEntity(mre); post.setRequestHeader("Content-Type", mre.getContentType()); post.setRequestHeader("Content-Length", String.valueOf(mre.getContentLength())); } else if (request.getEntityWriter() != null) { post.setRequestEntity(new EntityWriterRequestEntity(request.getEntityWriter(), computeAndSetContentLength(request, post))); } else if (request.getFile() != null) { File file = request.getFile(); if (!file.isFile()) { throw new IOException( String.format(Thread.currentThread() + "File %s is not a file or doesn't exist", file.getAbsolutePath())); } post.setRequestHeader("Content-Length", String.valueOf(file.length())); try (FileInputStream fis = new FileInputStream(file)) { InputStreamRequestEntity r = new InputStreamRequestEntity(fis); post.setRequestEntity(r); post.setRequestHeader("Content-Length", String.valueOf(r.getContentLength())); } } else if (request.getBodyGenerator() != null) { Body body = request.getBodyGenerator().createBody(); try { int length = (int) body.getContentLength(); if (length < 0) { length = (int) request.getContentLength(); } // TODO: This is suboptimal if (length >= 0) { post.setRequestHeader("Content-Length", String.valueOf(length)); // This is totally sub optimal byte[] bytes = new byte[length]; ByteBuffer buffer = ByteBuffer.wrap(bytes); for (;;) { buffer.clear(); if (body.read(buffer) < 0) { break; } } post.setRequestEntity(new ByteArrayRequestEntity(bytes)); } } finally { try { body.close(); } catch (IOException e) { logger.warn("Failed to close request body: {}", e.getMessage(), e); } } } if (request.getHeaders().getFirstValue("Expect") != null && request.getHeaders().getFirstValue("Expect").equalsIgnoreCase("100-Continue")) { post.setUseExpectHeader(true); } method = post; } else { method = testMethodFactory.createMethod(methodName, request); } ProxyServer proxyServer = ProxyUtils.getProxyServer(config, request); if (proxyServer != null) { if (proxyServer.getPrincipal() != null) { Credentials defaultCredentials = new UsernamePasswordCredentials(proxyServer.getPrincipal(), proxyServer.getPassword()); client.getState().setProxyCredentials(new AuthScope(null, -1, AuthScope.ANY_REALM), defaultCredentials); } ProxyHost proxyHost = proxyServer == null ? null : new ProxyHost(proxyServer.getHost(), proxyServer.getPort()); client.getHostConfiguration().setProxyHost(proxyHost); } if (request.getLocalAddress() != null) { client.getHostConfiguration().setLocalAddress(request.getLocalAddress()); } method.setFollowRedirects(false); if (isNonEmpty(request.getCookies())) { method.setRequestHeader("Cookie", AsyncHttpProviderUtils.encodeCookies(request.getCookies())); } if (request.getHeaders() != null) { for (String name : request.getHeaders().keySet()) { if (!"host".equalsIgnoreCase(name)) { for (String value : request.getHeaders().get(name)) { method.setRequestHeader(name, value); } } } } if (request.getHeaders().getFirstValue("User-Agent") != null) { method.setRequestHeader("User-Agent", request.getHeaders().getFirstValue("User-Agent")); } else if (config.getUserAgent() != null) { method.setRequestHeader("User-Agent", config.getUserAgent()); } else { method.setRequestHeader("User-Agent", AsyncHttpProviderUtils.constructUserAgent(TestableApacheAsyncHttpProvider.class)); } if (config.isCompressionEnabled()) { Header acceptableEncodingHeader = method.getRequestHeader("Accept-Encoding"); if (acceptableEncodingHeader != null) { String acceptableEncodings = acceptableEncodingHeader.getValue(); if (!acceptableEncodings.contains("gzip")) { StringBuilder buf = new StringBuilder(acceptableEncodings); if (buf.length() > 1) { buf.append(","); } buf.append("gzip"); method.setRequestHeader("Accept-Encoding", buf.toString()); } } else { method.setRequestHeader("Accept-Encoding", "gzip"); } } if (request.getVirtualHost() != null) { String vs = request.getVirtualHost(); int index = vs.indexOf(":"); if (index > 0) { vs = vs.substring(0, index); } method.getParams().setVirtualHost(vs); } return method; }
From source file:com.buzzdavidson.spork.client.OWAClient.java
public void markMessageRead(String messageUrl) { String filename = messageUrl.substring(messageUrl.lastIndexOf("/") + 1); String query = String.format(OWA_QUERY_MARK_AS_READ, filename); WebDavMethod setRead = new WebDavMethod(inboxAddress + "/", OWA_METHOD_PROP_PATCH, OWA_HEADERS_MATCH); try {/*from ww w . j a v a 2 s .c o m*/ setRead.setRequestEntity(new StringRequestEntity(query, null, null)); logger.info("Marking message as read [" + filename + "]"); int status = client.executeMethod(setRead); if (logger.isDebugEnabled()) { logger.debug("Message request returned status code [" + status + "]"); } } catch (HttpException ex) { logger.error("Received HttpException fetching mail", ex); } catch (UnsupportedEncodingException ex) { logger.error("Received UnsupportedEncodingException fetching mail", ex); } catch (IOException ex) { logger.error("Received IOException fetching mail", ex); } }
From source file:hoot.services.controllers.ogr.TranslatorResource.java
/** * <NAME>OGR-LTDS Translation Service</NAME> * <DESCRIPTION>//from w w w . j ava 2 s .c om * WARNING: THIS END POINT WILL BE DEPRECATED SOON * To translate osm element into OGR/LTDS format 2 services are available * http://localhost:8080/hoot-services/ogr/ltds/translate/{OSM element id}?translation={translation script} * </DESCRIPTION> * <PARAMETERS> * <translation> * relative path of translation script * </translation> * </PARAMETERS> * <OUTPUT> * TDS output * </OUTPUT> * <EXAMPLE> * <URL>http://localhost:8080/hoot-services/ogr/ltds/translate/-1669795?translation=MGCP.js</URL> * <REQUEST_TYPE>POST</REQUEST_TYPE> * <INPUT> * {some OSM XML} * </INPUT> * <OUTPUT>{"attrs":{"FCODE":"AP030","HCT":"0","UID":"d9c4b1df-066c-4ece-a583-76fec0056b58"},"tableName":"LAP030"}</OUTPUT> * </EXAMPLE> * @param id * @param translation * @param osmXml * @return */ @POST @Path("/ltds/translate/{id}") @Consumes(MediaType.TEXT_PLAIN) @Produces(MediaType.APPLICATION_JSON) public Response translateOsm(@PathParam("id") String id, @QueryParam("translation") final String translation, String osmXml) { String outStr = "unknown"; try { PostMethod mpost = new PostMethod("http://localhost:" + currentPort + "/osmtotds"); try { osmXml = osmXml.replace('"', '\''); JSONObject requestParams = new JSONObject(); requestParams.put("command", "translate"); requestParams.put("uid", id); requestParams.put("input", osmXml); requestParams.put("script", homeFolder + "/translations" + translation); requestParams.put("direction", "toogr"); StringRequestEntity requestEntity = new StringRequestEntity(requestParams.toJSONString(), "text/plain", "UTF-8"); mpost.setRequestEntity(requestEntity); mclient.executeMethod(mpost); String response = mpost.getResponseBodyAsString(); //r = client.execute(post); // String response = EntityUtils.toString(r.getEntity()); JSONParser par = new JSONParser(); JSONObject transRes = (JSONObject) par.parse(response); String tdsOSM = transRes.get("output").toString(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); StringReader strReader = new StringReader(tdsOSM); InputSource is = new InputSource(strReader); Document document = builder.parse(is); strReader.close(); String sFCode = null; JSONObject attrib = new JSONObject(); NodeList nodeList = document.getDocumentElement().getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node instanceof Element) { NodeList childNodes = node.getChildNodes(); for (int j = 0; j < childNodes.getLength(); j++) { Node cNode = childNodes.item(j); if (cNode instanceof Element) { String k = ((Element) cNode).getAttribute("k"); String v = ((Element) cNode).getAttribute("v"); attrib.put(k, v); if (k.equalsIgnoreCase("Feature Code")) { String[] parts = v.split(":"); sFCode = parts[0].trim(); } } } } } String sFields = getFields(sFCode); JSONObject ret = new JSONObject(); ret.put("tablenName", ""); ret.put("attrs", attrib); ret.put("fields", sFields); outStr = ret.toJSONString(); } catch (Exception ee) { ResourceErrorHandler.handleError("Failed upload: " + ee.toString(), Status.INTERNAL_SERVER_ERROR, log); } finally { mpost.releaseConnection(); } } catch (Exception e) { ResourceErrorHandler.handleError("Translation error: " + e.toString(), Status.INTERNAL_SERVER_ERROR, log); } return Response.ok(outStr, MediaType.APPLICATION_JSON).build(); }
From source file:com.cubeia.backoffice.wallet.client.WalletServiceClientHTTP.java
@Override public TransactionResult doTransaction(TransactionRequest transaction) { PostMethod method = new PostMethod(baseUrl + DO_TRANSACTION); log.info("Do Transaction, POST to: " + baseUrl + DO_TRANSACTION); try {//from w ww.j a va 2 s . co m String data = serialize(transaction); 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, TransactionResult.class); } if (statusCode == HttpStatus.SC_FORBIDDEN) { throw new NegativeBalanceException(-1L); } else { throw new RuntimeException("Failed to do transaction, RESPONSE CODE: " + statusCode); } } catch (NegativeBalanceException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } finally { method.releaseConnection(); } }
From source file:com.cloud.network.bigswitch.BigSwitchBcfApi.java
protected <T> String executeUpdateObject(final T newObject, final String uri, final Map<String, String> parameters) throws BigSwitchBcfApiException, IllegalArgumentException { checkInvariants();//from www . j ava 2s. c o m PutMethod pm = (PutMethod) createMethod("put", uri, _port); setHttpHeader(pm); try { pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), CONTENT_JSON, null)); } catch (UnsupportedEncodingException e) { throw new BigSwitchBcfApiException("Failed to encode json request body", e); } executeMethod(pm); String hash = checkResponse(pm, "BigSwitch HTTP update failed: "); pm.releaseConnection(); return hash; }
From source file:net.jadler.AbstractJadlerStubbingIntegrationTest.java
@Test public void havingParameterPOST() throws Exception { final String body = "p1=p1v1&p2=p2v1&p2=p2v2&p3=&p4&url%20encoded=url%20encoded"; onRequest().havingParameter("p1").havingParameter("p1", hasSize(1)) .havingParameter("p1", everyItem(not(isEmptyOrNullString()))) .havingParameter("p1", contains("p1v1")).havingParameterEqualTo("p1", "p1v1").havingParameter("p2") .havingParameter("p2", hasSize(3)).havingParameter("p2", hasItems("p2v1", "p2v2", "p2v3")) .havingParameterEqualTo("p2", "p2v1").havingParameterEqualTo("p2", "p2v2") .havingParameterEqualTo("p2", "p2v3").havingParameters("p1", "p2").havingParameter("p3") .havingParameter("p3", contains("")).havingParameterEqualTo("p3", "").havingParameter("p4") .havingParameter("p4", contains("")).havingParameterEqualTo("p4", "") .havingParameter("p5", nullValue()).havingParameter("url%20encoded", contains("url%20encoded")) .havingBodyEqualTo(body).respond().withStatus(201); final PostMethod method = new PostMethod("http://localhost:" + port() + "?p2=p2v3"); method.setRequestEntity(new StringRequestEntity(body, "application/x-www-form-urlencoded", "UTF-8")); int status = client.executeMethod(method); assertThat(status, is(201));/*from ww w. ja v a2s .c o m*/ method.releaseConnection(); }
From source file:com.cubeia.backoffice.users.client.UserServiceClientHTTP.java
@Override public UserQueryResult findUsers(Long userId, String name, int offset, int limit, UserOrder sortOrder, boolean ascending) { PutMethod method = new PutMethod(baseUrl + QUERY); UserQuery request = new UserQuery(); request.setUserId(userId);/* w w w. java2s .com*/ request.setUserName(name); request.setQueryOffset(offset); request.setQueryLimit(limit); request.setAscending(ascending); request.setOrder(sortOrder); try { 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, UserQueryResult.class); } else { throw new RuntimeException("Failed to query users, RESPONSE CODE: " + statusCode); } } catch (Exception e) { throw new RuntimeException(e); } finally { method.releaseConnection(); } }