List of usage examples for org.apache.commons.httpclient.methods RequestEntity RequestEntity
RequestEntity
From source file:davmail.exchange.dav.ExchangeDavMethod.java
/** * Create PROPPATCH method.//from w ww . j a v a2 s .c o m * * @param path path */ public ExchangeDavMethod(String path) { super(path); setRequestEntity(new RequestEntity() { byte[] content; public boolean isRepeatable() { return true; } public void writeRequest(OutputStream outputStream) throws IOException { if (content == null) { content = generateRequestContent(); } outputStream.write(content); } public long getContentLength() { if (content == null) { content = generateRequestContent(); } return content.length; } public String getContentType() { return "text/xml;charset=UTF-8"; } }); }
From source file:davmail.exchange.dav.ExchangePropPatchMethod.java
/** * Create PROPPATCH method.//from w w w . j a v a 2 s .c o m * * @param path path * @param propertyValues property values */ public ExchangePropPatchMethod(String path, Set<PropertyValue> propertyValues) { super(path); this.propertyValues = propertyValues; setRequestEntity(new RequestEntity() { byte[] content; public boolean isRepeatable() { return true; } public void writeRequest(OutputStream outputStream) throws IOException { if (content == null) { content = generateRequestContent(); } outputStream.write(content); } public long getContentLength() { if (content == null) { content = generateRequestContent(); } return content.length; } public String getContentType() { return "text/xml;charset=UTF-8"; } }); }
From source file:davmail.exchange.ews.EWSMethod.java
/** * Build EWS method/*from w ww . ja v a2s .co m*/ * * @param itemType item type * @param methodName method name * @param responseCollectionName item response collection name */ public EWSMethod(String itemType, String methodName, String responseCollectionName) { super("/ews/exchange.asmx"); this.itemType = itemType; this.methodName = methodName; this.responseCollectionName = responseCollectionName; if (Settings.getBooleanProperty("davmail.acceptEncodingGzip", true) && !Level.DEBUG.toString().equals(Settings.getProperty("log4j.logger.httpclient.wire"))) { setRequestHeader("Accept-Encoding", "gzip"); } setRequestEntity(new RequestEntity() { byte[] content; public boolean isRepeatable() { return true; } public void writeRequest(OutputStream outputStream) throws IOException { if (content == null) { content = generateSoapEnvelope(); } outputStream.write(content); } public long getContentLength() { if (content == null) { content = generateSoapEnvelope(); } return content.length; } public String getContentType() { return "text/xml; charset=UTF-8"; } }); }
From source file:com.denimgroup.threadfix.importer.impl.remoteprovider.utils.DefaultRequestConfigurer.java
private RequestEntity getRequestEntity() { return new RequestEntity() { @Override/*from w w w.j a v a 2 s .c om*/ public boolean isRepeatable() { return false; } @Override public void writeRequest(OutputStream out) throws IOException { out.write(requestBody.getBytes()); } @Override public long getContentLength() { return requestBody.length(); } @Override public String getContentType() { return requestBodyContentType; } }; }
From source file:com.sun.jersey.client.apache.DefaultApacheHttpMethodExecutor.java
@Override public void executeMethod(final HttpMethod method, final ClientRequest cr) { final Map<String, Object> props = cr.getProperties(); method.setDoAuthentication(true);/* w w w . j a v a 2s . c om*/ final HttpMethodParams methodParams = method.getParams(); // Set the handle cookies property if (!cr.getPropertyAsFeature(ApacheHttpClientConfig.PROPERTY_HANDLE_COOKIES)) { methodParams.setCookiePolicy(CookiePolicy.IGNORE_COOKIES); } // Set the interactive and credential provider properties if (cr.getPropertyAsFeature(ApacheHttpClientConfig.PROPERTY_INTERACTIVE)) { CredentialsProvider provider = (CredentialsProvider) props .get(ApacheHttpClientConfig.PROPERTY_CREDENTIALS_PROVIDER); if (provider == null) { provider = DEFAULT_CREDENTIALS_PROVIDER; } methodParams.setParameter(CredentialsProvider.PROVIDER, provider); } else { methodParams.setParameter(CredentialsProvider.PROVIDER, null); } // Set the read timeout final Integer readTimeout = (Integer) props.get(ApacheHttpClientConfig.PROPERTY_READ_TIMEOUT); if (readTimeout != null) { methodParams.setSoTimeout(readTimeout); } if (method instanceof EntityEnclosingMethod) { final EntityEnclosingMethod entMethod = (EntityEnclosingMethod) method; if (cr.getEntity() != null) { final RequestEntityWriter re = getRequestEntityWriter(cr); final Integer chunkedEncodingSize = (Integer) props .get(ApacheHttpClientConfig.PROPERTY_CHUNKED_ENCODING_SIZE); if (chunkedEncodingSize != null) { // There doesn't seems to be a way to set the chunk size. entMethod.setContentChunked(true); // It is not possible for a MessageBodyWriter to modify // the set of headers before writing out any bytes to // the OutputStream // This makes it impossible to use the multipart // writer that modifies the content type to add a boundary // parameter writeOutBoundHeaders(cr.getHeaders(), method); // Do not buffer the request entity when chunked encoding is // set entMethod.setRequestEntity(new RequestEntity() { @Override public boolean isRepeatable() { return false; } @Override public void writeRequest(OutputStream out) throws IOException { re.writeRequestEntity(out); } @Override public long getContentLength() { return re.getSize(); } @Override public String getContentType() { return re.getMediaType().toString(); } }); } else { entMethod.setContentChunked(false); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { re.writeRequestEntity(new CommittingOutputStream(baos) { @Override protected void commit() throws IOException { writeOutBoundHeaders(cr.getMetadata(), method); } }); } catch (IOException ex) { throw new ClientHandlerException(ex); } final byte[] content = baos.toByteArray(); entMethod.setRequestEntity(new RequestEntity() { @Override public boolean isRepeatable() { return true; } @Override public void writeRequest(OutputStream out) throws IOException { out.write(content); } @Override public long getContentLength() { return content.length; } @Override public String getContentType() { return re.getMediaType().toString(); } }); } } else { writeOutBoundHeaders(cr.getHeaders(), method); } } else { writeOutBoundHeaders(cr.getHeaders(), method); // Follow redirects method.setFollowRedirects(cr.getPropertyAsFeature(ApacheHttpClientConfig.PROPERTY_FOLLOW_REDIRECTS)); } try { httpClient.executeMethod(getHostConfiguration(httpClient, props), method, getHttpState(props)); } catch (Exception e) { method.releaseConnection(); throw new ClientHandlerException(e); } }
From source file:edu.ucsd.xmlrpc.xmlrpc.client.XmlRpcCommonsTransport.java
protected void writeRequest(final ReqWriter pWriter) throws XmlRpcException { method.setRequestEntity(new RequestEntity() { public boolean isRepeatable() { return true; }//w ww .jav a 2 s .c o m public void writeRequest(OutputStream pOut) throws IOException { try { /* Make sure, that the socket is not closed by replacing it with our * own BufferedOutputStream. */ OutputStream ostream; if (isUsingByteArrayOutput(config)) { // No need to buffer the output. ostream = new FilterOutputStream(pOut) { public void close() throws IOException { flush(); } }; } else { ostream = new BufferedOutputStream(pOut) { public void close() throws IOException { flush(); } }; } pWriter.write(ostream); } catch (XmlRpcException e) { throw new XmlRpcIOException(e); } catch (SAXException e) { throw new XmlRpcIOException(e); } } public long getContentLength() { return contentLength; } public String getContentType() { return "text/xml"; } }); try { int redirectAttempts = 0; for (;;) { client.executeMethod(method); if (!isRedirectRequired()) { break; } if (redirectAttempts++ > MAX_REDIRECT_ATTEMPTS) { throw new XmlRpcException("Too many redirects."); } resetClientForRedirect(); } } catch (XmlRpcIOException e) { Throwable t = e.getLinkedException(); if (t instanceof XmlRpcException) { throw (XmlRpcException) t; } else { throw new XmlRpcException("Unexpected exception: " + t.getMessage(), t); } } catch (IOException e) { throw new XmlRpcException("I/O error while communicating with HTTP server: " + e.getMessage(), e); } }
From source file:com.noelios.restlet.ext.httpclient.HttpMethodCall.java
/** * Sends the request to the client. Commits the request line, headers and * optional entity and send them over the network. * /*from w ww. jav a 2 s. co m*/ * @param request * The high-level request. * @return The result status. */ @Override public Status sendRequest(Request request) { Status result = null; try { final Representation entity = request.getEntity(); // Set the request headers for (final Parameter header : getRequestHeaders()) { getHttpMethod().addRequestHeader(header.getName(), header.getValue()); } // For those method that accept enclosing entities, provide it if ((entity != null) && (getHttpMethod() instanceof EntityEnclosingMethod)) { final EntityEnclosingMethod eem = (EntityEnclosingMethod) getHttpMethod(); eem.setRequestEntity(new RequestEntity() { public long getContentLength() { return entity.getSize(); } public String getContentType() { return (entity.getMediaType() != null) ? entity.getMediaType().toString() : null; } public boolean isRepeatable() { return !entity.isTransient(); } public void writeRequest(OutputStream os) throws IOException { entity.write(os); } }); } // Ensure that the connection is active this.clientHelper.getHttpClient().executeMethod(getHttpMethod()); // Now we can access the status code, this MUST happen after closing // any open request stream. result = new Status(getStatusCode(), null, getReasonPhrase(), null); // If there is no response body, immediately release the connection if (getHttpMethod().getResponseBodyAsStream() == null) { getHttpMethod().releaseConnection(); } } catch (IOException ioe) { this.clientHelper.getLogger().log(Level.WARNING, "An error occurred during the communication with the remote HTTP server.", ioe); result = new Status(Status.CONNECTOR_ERROR_COMMUNICATION, ioe); // Release the connection getHttpMethod().releaseConnection(); } return result; }
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 va 2 s . co 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:org.ambraproject.service.crossref.CrossRefLookupServiceImpl.java
private PostMethod createCrossRefPost(String searchString) { StringBuilder builder = new StringBuilder(); //Example query to post: //["Young GC,Analytical methods in palaeobiogeography, and the role of early vertebrate studies;Palaeoworld;19;160-173"] //Use toJSON to encode strings with proper escaping final String json = "[" + (new Gson()).toJson(searchString) + "]"; if (this.crossRefUrl == null) { throw new RuntimeException("ambra.services.crossref.query.url value not found in configuration."); }/*from ww w .j av a 2 s. c om*/ return new PostMethod(this.crossRefUrl) { { addRequestHeader("Content-Type", "application/json"); setRequestEntity(new RequestEntity() { @Override public boolean isRepeatable() { return false; } @Override public void writeRequest(OutputStream outputStream) throws IOException { outputStream.write(json.getBytes()); } @Override public long getContentLength() { return json.getBytes().length; } @Override public String getContentType() { return "application/json"; } }); } }; }
From source file:org.ambraproject.service.orcid.OrcidServiceImpl.java
private PostMethod createOrcidAccessTokenQuery(String authorizationCode) throws UnsupportedEncodingException { final String query = "code=" + authorizationCode + "&client_id=" + this.clientID + "&scope=" + URLEncoder.encode(API_SCOPE, "UTF-8") + "&client_secret=" + this.clientSecret + "&grant_type=authorization_code"; return new PostMethod(this.tokenEndPoint) { {//from w ww . j a va2 s . com setRequestEntity(new RequestEntity() { @Override public boolean isRepeatable() { return false; } @Override public void writeRequest(OutputStream outputStream) throws IOException { outputStream.write(query.getBytes()); } @Override public long getContentLength() { return query.getBytes().length; } @Override public String getContentType() { return "application/x-www-form-urlencoded"; } }); } }; }