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:com.twinsoft.convertigo.beans.connectors.HttpConnector.java
public byte[] getData(Context context) throws IOException, EngineException { HttpMethod method = null;/* w w w. j a v a 2 s .c o m*/ try { // Fire event for plugins long t0 = System.currentTimeMillis(); Engine.theApp.pluginsManager.fireHttpConnectorGetDataStart(context); // Retrieving httpState getHttpState(context); Engine.logBeans.trace("(HttpConnector) Retrieving data as a bytes array..."); Engine.logBeans.debug("(HttpConnector) Connecting to: " + sUrl); // Setting the referer referer = sUrl; URL url = null; url = new URL(sUrl); // Proxy configuration Engine.theApp.proxyManager.setProxy(hostConfiguration, httpState, url); Engine.logBeans.debug("(HttpConnector) Https: " + https); String host = ""; int port = -1; if (sUrl.toLowerCase().startsWith("https:")) { if (!https) { Engine.logBeans.debug("(HttpConnector) Setting up SSL properties"); certificateManager.collectStoreInformation(context); } url = new URL(sUrl); host = url.getHost(); port = url.getPort(); if (port == -1) port = 443; Engine.logBeans.debug("(HttpConnector) Host: " + host + ":" + port); Engine.logBeans .debug("(HttpConnector) CertificateManager has changed: " + certificateManager.hasChanged); if (certificateManager.hasChanged || (!host.equalsIgnoreCase(hostConfiguration.getHost())) || (hostConfiguration.getPort() != port)) { Engine.logBeans.debug("(HttpConnector) Using MySSLSocketFactory for creating the SSL socket"); Protocol myhttps = new Protocol("https", MySSLSocketFactory.getSSLSocketFactory(certificateManager.keyStore, certificateManager.keyStorePassword, certificateManager.trustStore, certificateManager.trustStorePassword, this.trustAllServerCertificates), port); hostConfiguration.setHost(host, port, myhttps); } sUrl = url.getFile(); Engine.logBeans.debug("(HttpConnector) Updated URL for SSL purposes: " + sUrl); } else { url = new URL(sUrl); host = url.getHost(); port = url.getPort(); Engine.logBeans.debug("(HttpConnector) Host: " + host + ":" + port); hostConfiguration.setHost(host, port); } AbstractHttpTransaction httpTransaction = (AbstractHttpTransaction) context.transaction; // Retrieve HTTP method HttpMethodType httpVerb = httpTransaction.getHttpVerb(); String sHttpVerb = httpVerb.name(); final String sCustomHttpVerb = httpTransaction.getCustomHttpVerb(); if (sCustomHttpVerb.length() > 0) { Engine.logBeans.debug( "(HttpConnector) HTTP verb: " + sHttpVerb + " overridden to '" + sCustomHttpVerb + "'"); switch (httpVerb) { case GET: method = new GetMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case POST: method = new PostMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case PUT: method = new PutMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case DELETE: method = new DeleteMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case HEAD: method = new HeadMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case OPTIONS: method = new OptionsMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case TRACE: method = new TraceMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; } } else { Engine.logBeans.debug("(HttpConnector) HTTP verb: " + sHttpVerb); switch (httpVerb) { case GET: method = new GetMethod(sUrl); break; case POST: method = new PostMethod(sUrl); break; case PUT: method = new PutMethod(sUrl); break; case DELETE: method = new DeleteMethod(sUrl); break; case HEAD: method = new HeadMethod(sUrl); break; case OPTIONS: method = new OptionsMethod(sUrl); break; case TRACE: method = new TraceMethod(sUrl); break; } } // Setting HTTP parameters boolean hasUserAgent = false; for (List<String> httpParameter : httpParameters) { String key = httpParameter.get(0); String value = httpParameter.get(1); if (key.equalsIgnoreCase("host") && !value.equals(host)) { value = host; } if (!key.startsWith(DYNAMIC_HEADER_PREFIX)) { method.setRequestHeader(key, value); } if (HeaderName.UserAgent.is(key)) { hasUserAgent = true; } } // set user-agent header if not found if (!hasUserAgent) { HeaderName.UserAgent.setRequestHeader(method, getUserAgent(context)); } // Setting POST or PUT parameters if any Engine.logBeans.debug("(HttpConnector) Setting " + httpVerb + " data"); if (method instanceof EntityEnclosingMethod) { EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) method; AbstractHttpTransaction transaction = (AbstractHttpTransaction) context.requestedObject; if (doMultipartFormData) { RequestableHttpVariable body = (RequestableHttpVariable) httpTransaction .getVariable(Parameter.HttpBody.getName()); if (body != null && body.getDoFileUploadMode() == DoFileUploadMode.multipartFormData) { String stringValue = httpTransaction.getParameterStringValue(Parameter.HttpBody.getName()); String filepath = Engine.theApp.filePropertyManager.getFilepathFromProperty(stringValue, getProject().getName()); File file = new File(filepath); if (file.exists()) { HeaderName.ContentType.setRequestHeader(method, contentType); entityEnclosingMethod.setRequestEntity(new FileRequestEntity(file, contentType)); } else { throw new FileNotFoundException(file.getAbsolutePath()); } } else { List<Part> parts = new LinkedList<Part>(); for (RequestableVariable variable : transaction.getVariablesList()) { if (variable instanceof RequestableHttpVariable) { RequestableHttpVariable httpVariable = (RequestableHttpVariable) variable; if ("POST".equals(httpVariable.getHttpMethod())) { Object httpObjectVariableValue = transaction .getVariableValue(httpVariable.getName()); if (httpVariable.isMultiValued()) { if (httpObjectVariableValue instanceof Collection<?>) { for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) { addFormDataPart(parts, httpVariable, httpVariableValue); } } } else { addFormDataPart(parts, httpVariable, httpObjectVariableValue); } } } } MultipartRequestEntity mre = new MultipartRequestEntity( parts.toArray(new Part[parts.size()]), entityEnclosingMethod.getParams()); HeaderName.ContentType.setRequestHeader(method, mre.getContentType()); entityEnclosingMethod.setRequestEntity(mre); } } else if (MimeType.TextXml.is(contentType)) { final MimeMultipart[] mp = { null }; for (RequestableVariable variable : transaction.getVariablesList()) { if (variable instanceof RequestableHttpVariable) { RequestableHttpVariable httpVariable = (RequestableHttpVariable) variable; if (httpVariable.getDoFileUploadMode() == DoFileUploadMode.MTOM) { Engine.logBeans.trace( "(HttpConnector) Variable " + httpVariable.getName() + " detected as MTOM"); MimeMultipart mimeMultipart = mp[0]; try { if (mimeMultipart == null) { Engine.logBeans.debug("(HttpConnector) Preparing the MTOM request"); mimeMultipart = new MimeMultipart("related; type=\"application/xop+xml\""); MimeBodyPart bp = new MimeBodyPart(); bp.setText(postQuery, "UTF-8"); bp.setHeader(HeaderName.ContentType.value(), contentType); mimeMultipart.addBodyPart(bp); } Object httpObjectVariableValue = transaction .getVariableValue(httpVariable.getName()); if (httpVariable.isMultiValued()) { if (httpObjectVariableValue instanceof Collection<?>) { for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) { addMtomPart(mimeMultipart, httpVariable, httpVariableValue); } } } else { addMtomPart(mimeMultipart, httpVariable, httpObjectVariableValue); } mp[0] = mimeMultipart; } catch (Exception e) { Engine.logBeans.warn( "(HttpConnector) Failed to add MTOM part for " + httpVariable.getName(), e); } } } } if (mp[0] == null) { entityEnclosingMethod.setRequestEntity( new StringRequestEntity(postQuery, MimeType.TextXml.value(), "UTF-8")); } else { Engine.logBeans.debug("(HttpConnector) Commit the MTOM request with the ContentType: " + mp[0].getContentType()); HeaderName.ContentType.setRequestHeader(method, mp[0].getContentType()); entityEnclosingMethod.setRequestEntity(new RequestEntity() { @Override public void writeRequest(OutputStream outputStream) throws IOException { try { mp[0].writeTo(outputStream); } catch (MessagingException e) { new IOException(e); } } @Override public boolean isRepeatable() { return true; } @Override public String getContentType() { return mp[0].getContentType(); } @Override public long getContentLength() { return -1; } }); } } else { String charset = httpTransaction.getComputedUrlEncodingCharset(); HeaderName.ContentType.setRequestHeader(method, contentType); entityEnclosingMethod .setRequestEntity(new StringRequestEntity(postQuery, contentType, charset)); } } // Getting the result Engine.logBeans.debug("(HttpConnector) HttpClient: getting response body"); byte[] result = executeMethod(method, context); Engine.logBeans.debug("(HttpConnector) Total read bytes: " + ((result != null) ? result.length : 0)); // Fire event for plugins long t1 = System.currentTimeMillis(); Engine.theApp.pluginsManager.fireHttpConnectorGetDataEnd(context, t0, t1); fireDataChanged(new ConnectorEvent(this, result)); return result; } finally { if (method != null) method.releaseConnection(); } }
From source file:muki.tool.JavaCompilationDeploymentTestCase.java
@Test public void testPostOperationInvalidCharsXml() throws Exception { String url = URL_RESOURCE2 + "/pathPostOperationInvalidCharsXml"; PostMethod method = new PostMethod(url); String param = this.getXmlTrackInvalidChars(); method.setRequestEntity(new StringRequestEntity(param, "application/xml", null)); int statusCode = this.getHttpClient().executeMethod(method); assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_OK); byte[] responseBody = method.getResponseBody(); String xmlResponse = new String(responseBody); assertTrue(xmlResponse.indexOf("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>") > -1); assertTrue(xmlResponse.indexOf("<title><My Track 1/> & 'My Track' "2"</title>") > -1); }
From source file:muki.tool.JavaCompilationDeploymentTestCase.java
/** * The JSON string contains special chars in the values: '{', '}', '"' that must * be enconded and arrive correctly on the server. *//* w w w. j a v a 2s . c om*/ @Test public void testPostOperationInvalidCharsJson() throws Exception { String url = URL_RESOURCE2 + "/pathPostOperationInvalidCharsJson"; PostMethod method = new PostMethod(url); String param = this.getJsonTrackInvalidChars(); method.setRequestEntity(new StringRequestEntity(param, "application/json", null)); int statusCode = this.getHttpClient().executeMethod(method); assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_OK); byte[] responseBody = method.getResponseBody(); String jsonResponse = new String(responseBody); assertTrue(jsonResponse.indexOf("{My {\\\"Track} 1 & {'My Track' ") > -1); }
From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java
public void sendNotificationToUsers(Notification notification, int learningObjectId, int instanceId, int[] receiverUserIds, int senderUserId) throws Exception { String uri = String.format( _baseUri + "/LearningObjectService.svc/learningObjects/%s/instances/%s/NotificationToUsers", learningObjectId, instanceId); PostMethod method = (PostMethod) getInitializedHttpMethod(_httpClient, uri, HttpMethodType.POST); String reportAsXml = serializeNotificationToWrappedXML(notification); String userIdsAsXml = serializeUserIdsToWrappedXML(receiverUserIds); String senderUserIdAsXml = "<senderUserId>" + Integer.toString(senderUserId) + "</senderUserId>"; String openingTag = "<SendNotificationToUsers xmlns=\"http://tempuri.org/\">"; String closingTag = "</SendNotificationToUsers>"; StringBuilder xmlBuilder = new StringBuilder(); xmlBuilder.append(openingTag);//from w w w.j a v a 2 s .c o m xmlBuilder.append(reportAsXml); xmlBuilder.append(userIdsAsXml); xmlBuilder.append(senderUserIdAsXml); xmlBuilder.append(closingTag); method.setRequestEntity(new StringRequestEntity(xmlBuilder.toString(), "text/xml", "UTF-8")); try { int statusCode = _httpClient.executeMethod(method); // POST methods, may return 200, 201, 204 if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED && statusCode != HttpStatus.SC_NOT_MODIFIED) { throw new HTTPException(statusCode); } } catch (Exception ex) { ExceptionHandler.handle(ex); } finally { method.releaseConnection(); } }
From source file:com.znsx.cms.service.impl.DeviceManagerImpl.java
private List<Element> requestSubDeviceStatus(String subSn, List<String> devices) { String url = Configuration.getInstance().getProperties(subSn); // url?/*w ww . j a v a2 s . c om*/ if (StringUtils.isBlank(url)) { System.out.println("Sub platform[" + subSn + "] not in config.properties !"); return new LinkedList<Element>(); } // urlIP:Port? String[] address = url.split(":"); if (address.length != 2) { System.out.println("Sub platform[" + subSn + "] config url[" + url + "] is invalid !"); return new LinkedList<Element>(); } // ? if (isSelfAddress(address[0])) { System.out.println("Sub platform[" + subSn + "] address can not be my address !"); return new LinkedList<Element>(); } StringBuffer sb = new StringBuffer(); sb.append("<Request Method=\"List_Device_Status\" Cmd=\"1017\">"); sb.append(System.getProperty("line.separator")); for (String sn : devices) { sb.append(" <Device StandardNumber=\""); sb.append(sn); sb.append("\" />"); sb.append(System.getProperty("line.separator")); } sb.append("</Request>"); String body = sb.toString(); HttpClient client = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true)); client.getHttpConnectionManager().getParams().setConnectionTimeout(20000); PostMethod method = new PostMethod("http://" + url + "/cms/list_device_status.xml"); System.out.println("Send request to " + url + " body is :"); System.out.println(body); try { RequestEntity entity = new StringRequestEntity(body, "application/xml", "utf8"); method.setRequestEntity(entity); client.executeMethod(method); // SAXBuilder builder = new SAXBuilder(); Document respDoc = builder.build(method.getResponseBodyAsStream()); String code = respDoc.getRootElement().getAttributeValue("Code"); if (ErrorCode.SUCCESS.equals(code)) { List<Element> list = respDoc.getRootElement().getChildren("Device"); return list; } } catch (Exception e) { e.printStackTrace(); } finally { method.releaseConnection(); } return new LinkedList<Element>(); }
From source file:org.activiti.kickstart.service.alfresco.AlfrescoKickstartServiceImpl.java
protected int executeFormConfigUpload(String formConfig) { HttpState state = new HttpState(); state.setCredentials(new AuthScope(null, AuthScope.ANY_PORT), new UsernamePasswordCredentials(cmisUser, cmisPassword)); LOGGER.info("Deploying form config XML: "); prettyLogXml(formConfig);//from w w w.ja va2 s . c om PostMethod postMethod = new PostMethod(FORM_CONFIG_UPLOAD_URL); try { postMethod.setRequestEntity(new StringRequestEntity(formConfig, "application/xml", "UTF-8")); HttpClient httpClient = new HttpClient(); int result = httpClient.executeMethod(null, postMethod, state); // Display status code LOGGER.info("Response status code: " + result); // Display response LOGGER.info("Response body: "); LOGGER.info(postMethod.getResponseBodyAsString()); return result; } catch (Throwable t) { System.err.println("Error: " + t.getMessage()); t.printStackTrace(); } finally { postMethod.releaseConnection(); } throw new RuntimeException("Programmatic error. You shouldn't be here."); }
From source file:org.ala.client.util.RestfulClient.java
/** * Makes a POST request to the specified URL and passes the provided JSON Object * * @param url URL Endpoint//www.ja v a 2 s . c o m * @param mimeType return mimeType * @param jsonRequestBody JSON Object to post to URL * @param headers Name/Value pairs of HTTP Request Headers to be set on the request * @return [0]: status code; [1]: a JSON encoded response * @throws IOException * @throws HttpException */ public Object[] restPost(String url, String contentType, String jsonRequestBody, Map<String, String> headers) throws HttpException, IOException { PostMethod post = null; String resp = null; int statusCode = 0; try { post = new PostMethod(url); for (Map.Entry<String, String> entry : headers.entrySet()) { post.setRequestHeader(new Header(entry.getKey(), entry.getValue())); } RequestEntity entity = new StringRequestEntity(jsonRequestBody, contentType, ENCODE_TYPE); post.setRequestEntity(entity); statusCode = client.executeMethod(post); if (statusCode == HttpStatus.SC_OK) { resp = post.getResponseBodyAsString(); } } finally { if (post != null) { post.releaseConnection(); } } Object[] o = new Object[] { statusCode, resp }; return o; }
From source file:org.ala.spatial.util.CitationService.java
public static String postInfo(String url, Map params, boolean asBody) { try {//from ww w. j a va 2s . c om HttpClient client = new HttpClient(); PostMethod post = new PostMethod(url); // testurl post.addRequestHeader("Accept", "application/json, text/javascript, */*"); // add the post params if (params != null) { if (!asBody) { for (Iterator ekeys = params.keySet().iterator(); ekeys.hasNext();) { String key = (String) ekeys.next(); String value = (String) params.get(key); post.addParameter(key, URLEncoder.encode(value, "UTF-8")); } } else { StringBuilder sbParams = new StringBuilder(); for (Iterator ekeys = params.keySet().iterator(); ekeys.hasNext();) { String key = (String) ekeys.next(); String value = (String) params.get(key); sbParams.append(value); } RequestEntity entity = new StringRequestEntity(sbParams.toString(), "text/plain", "UTF-8"); post.setRequestEntity(entity); } } int result = client.executeMethod(post); String slist = post.getResponseBodyAsString(); return slist; } catch (Exception ex) { System.out.println("postInfo.error:"); ex.printStackTrace(System.out); } return null; }
From source file:org.ala.util.PartialIndex.java
private void postIndexUpdate(String[] guids) throws Exception { PostMethod post = new PostMethod(bieURL + "/ws/admin/reindex"); logger.info("Sending index list starting with " + guids[0] + " " + guids.length); String json = mapper.writeValueAsString(guids); post.setRequestEntity(new StringRequestEntity(json, "json", "utf-8")); httpClient.executeMethod(post);//from w w w. j a v a 2s .c o m }
From source file:org.alfresco.repo.remoteconnector.RemoteConnectorRequestImpl.java
public void setRequestBody(String body) { try {/*from ww w . ja v a 2 s. c om*/ requestBody = new StringRequestEntity(body, getContentType(), "UTF-8"); } catch (UnsupportedEncodingException e) { } // Can't occur }