List of usage examples for org.apache.commons.httpclient.methods RequestEntity RequestEntity
RequestEntity
From source file:org.apache.jmeter.protocol.http.sampler.SoapSampler.java
/** * Send POST data from <code>Entry</code> to the open connection. * * @param post POST request to send/* w ww .j a va 2 s . c o m*/ * @param length the length of the content */ private String sendPostData(PostMethod post, final int length) { // Buffer to hold the post body, except file content StringBuilder postedBody = new StringBuilder(1000); final String xmlFile = getXmlFile(); if (xmlFile != null && xmlFile.length() > 0) { File xmlFileAsFile = new File(xmlFile); if (!(xmlFileAsFile.exists() && xmlFileAsFile.canRead())) { throw new IllegalArgumentException(JMeterUtils.getResString("soap_sampler_file_invalid") // $NON-NLS-1$ + xmlFileAsFile.getAbsolutePath()); } // We just add placeholder text for file content postedBody.append("Filename: ").append(xmlFile).append("\n"); postedBody.append("<actual file content, not shown here>"); post.setRequestEntity(new RequestEntity() { @Override public boolean isRepeatable() { return true; } @Override public void writeRequest(OutputStream out) throws IOException { InputStream in = null; try { in = new BufferedInputStream(new FileInputStream(xmlFile)); IOUtils.copy(in, out); out.flush(); } finally { IOUtils.closeQuietly(in); } } @Override public long getContentLength() { switch (length) { case -1: return -1; case 0: // No header provided return new File(xmlFile).length(); default: return length; } } @Override public String getContentType() { // TODO do we need to add a charset for the file contents? return DEFAULT_CONTENT_TYPE; // $NON-NLS-1$ } }); } else { postedBody.append(getXmlData()); post.setRequestEntity(new RequestEntity() { @Override public boolean isRepeatable() { return true; } @Override public void writeRequest(OutputStream out) throws IOException { // charset must agree with content-type below IOUtils.write(getXmlData(), out, ENCODING); // $NON-NLS-1$ out.flush(); } @Override public long getContentLength() { try { return getXmlData().getBytes(ENCODING).length; // so we don't generate chunked encoding } catch (UnsupportedEncodingException e) { log.warn(e.getLocalizedMessage()); return -1; // will use chunked encoding } } @Override public String getContentType() { return DEFAULT_CONTENT_TYPE + "; charset=" + ENCODING; // $NON-NLS-1$ } }); } return postedBody.toString(); }
From source file:org.apache.solr.client.solrj.impl.CommonsHttpSolrServer.java
public NamedList<Object> request(final SolrRequest request, ResponseParser processor) throws SolrServerException, IOException { HttpMethod method = null;// www . j a va 2 s . c o m InputStream is = null; SolrParams params = request.getParams(); Collection<ContentStream> streams = requestWriter.getContentStreams(request); String path = requestWriter.getPath(request); if (path == null || !path.startsWith("/")) { path = "/select"; } ResponseParser parser = request.getResponseParser(); if (parser == null) { parser = _parser; } // The parser 'wt=' and 'version=' params are used instead of the original params ModifiableSolrParams wparams = new ModifiableSolrParams(); wparams.set(CommonParams.WT, parser.getWriterType()); wparams.set(CommonParams.VERSION, parser.getVersion()); if (params == null) { params = wparams; } else { params = new DefaultSolrParams(wparams, params); } if (_invariantParams != null) { params = new DefaultSolrParams(_invariantParams, params); } int tries = _maxRetries + 1; try { while (tries-- > 0) { // Note: since we aren't do intermittent time keeping // ourselves, the potential non-timeout latency could be as // much as tries-times (plus scheduling effects) the given // timeAllowed. try { if (SolrRequest.METHOD.GET == request.getMethod()) { if (streams != null) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!"); } method = new GetMethod(_baseURL + path + ClientUtils.toQueryString(params, false)); } else if (SolrRequest.METHOD.POST == request.getMethod()) { String url = _baseURL + path; boolean isMultipart = (streams != null && streams.size() > 1); if (streams == null || isMultipart) { PostMethod post = new PostMethod(url); post.getParams().setContentCharset("UTF-8"); if (!this.useMultiPartPost && !isMultipart) { post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); } List<Part> parts = new LinkedList<Part>(); Iterator<String> iter = params.getParameterNamesIterator(); while (iter.hasNext()) { String p = iter.next(); String[] vals = params.getParams(p); if (vals != null) { for (String v : vals) { if (this.useMultiPartPost || isMultipart) { parts.add(new StringPart(p, v, "UTF-8")); } else { post.addParameter(p, v); } } } } if (isMultipart) { int i = 0; for (ContentStream content : streams) { final ContentStream c = content; String charSet = null; PartSource source = new PartSource() { public long getLength() { return c.getSize(); } public String getFileName() { return c.getName(); } public InputStream createInputStream() throws IOException { return c.getStream(); } }; parts.add(new FilePart(c.getName(), source, c.getContentType(), charSet)); } } if (parts.size() > 0) { post.setRequestEntity(new MultipartRequestEntity( parts.toArray(new Part[parts.size()]), post.getParams())); } method = post; } // It is has one stream, it is the post body, put the params in the URL else { String pstr = ClientUtils.toQueryString(params, false); PostMethod post = new PostMethod(url + pstr); // post.setRequestHeader("connection", "close"); // Single stream as body // Using a loop just to get the first one final ContentStream[] contentStream = new ContentStream[1]; for (ContentStream content : streams) { contentStream[0] = content; break; } if (contentStream[0] instanceof RequestWriter.LazyContentStream) { post.setRequestEntity(new RequestEntity() { public long getContentLength() { return -1; } public String getContentType() { return contentStream[0].getContentType(); } public boolean isRepeatable() { return false; } public void writeRequest(OutputStream outputStream) throws IOException { ((RequestWriter.LazyContentStream) contentStream[0]).writeTo(outputStream); } }); } else { is = contentStream[0].getStream(); post.setRequestEntity( new InputStreamRequestEntity(is, contentStream[0].getContentType())); } method = post; } } else { throw new SolrServerException("Unsupported method: " + request.getMethod()); } } catch (NoHttpResponseException r) { // This is generally safe to retry on method.releaseConnection(); method = null; if (is != null) { is.close(); } // If out of tries then just rethrow (as normal error). if ((tries < 1)) { throw r; } //log.warn( "Caught: " + r + ". Retrying..." ); } } } catch (IOException ex) { log.error("####request####", ex); throw new SolrServerException("error reading streams", ex); } method.setFollowRedirects(_followRedirects); method.addRequestHeader("User-Agent", AGENT); if (_allowCompression) { method.setRequestHeader(new Header("Accept-Encoding", "gzip,deflate")); } // method.setRequestHeader("connection", "close"); try { // Execute the method. //System.out.println( "EXECUTE:"+method.getURI() ); int statusCode = _httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { StringBuilder msg = new StringBuilder(); msg.append(method.getStatusLine().getReasonPhrase()); msg.append("\n\n"); msg.append(method.getStatusText()); msg.append("\n\n"); msg.append("request: " + method.getURI()); throw new SolrException(statusCode, java.net.URLDecoder.decode(msg.toString(), "UTF-8")); } // Read the contents String charset = "UTF-8"; if (method instanceof HttpMethodBase) { charset = ((HttpMethodBase) method).getResponseCharSet(); } InputStream respBody = method.getResponseBodyAsStream(); // Jakarta Commons HTTPClient doesn't handle any // compression natively. Handle gzip or deflate // here if applicable. if (_allowCompression) { Header contentEncodingHeader = method.getResponseHeader("Content-Encoding"); if (contentEncodingHeader != null) { String contentEncoding = contentEncodingHeader.getValue(); if (contentEncoding.contains("gzip")) { //log.debug( "wrapping response in GZIPInputStream" ); respBody = new GZIPInputStream(respBody); } else if (contentEncoding.contains("deflate")) { //log.debug( "wrapping response in InflaterInputStream" ); respBody = new InflaterInputStream(respBody); } } else { Header contentTypeHeader = method.getResponseHeader("Content-Type"); if (contentTypeHeader != null) { String contentType = contentTypeHeader.getValue(); if (contentType != null) { if (contentType.startsWith("application/x-gzip-compressed")) { //log.debug( "wrapping response in GZIPInputStream" ); respBody = new GZIPInputStream(respBody); } else if (contentType.startsWith("application/x-deflate")) { //log.debug( "wrapping response in InflaterInputStream" ); respBody = new InflaterInputStream(respBody); } } } } } return processor.processResponse(respBody, charset); } catch (HttpException e) { throw new SolrServerException(e); } catch (IOException e) { throw new SolrServerException(e); } finally { method.releaseConnection(); if (is != null) { is.close(); } } }
From source file:org.apache.xmlrpc.client.XmlRpcCommonsTransport.java
protected void writeRequest(final ReqWriter pWriter) throws XmlRpcException { method.setRequestEntity(new RequestEntity() { public boolean isRepeatable() { return true; }//from www . ja v a 2 s.com 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(); } // See XMLRPC-173 public void write(byte[] b, int off, int len) throws IOException { out.write(b, off, len); } // See XMLRPC-173 public void write(byte[] b) throws IOException { out.write(b); } }; } 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:org.artifactory.cli.rest.RestClient.java
/** * post method with full settings//from ww w . java 2 s.co m * * @param uri Target URL * @param data Data to send * @param inputType Type of data which is sent * @param expectedStatus Expected return status * @param expectedResultType Expected response media type * @param printStream True if should print response stream to system.out * @param timeout Request timeout * @param credentials For authentication * @return byte[] - Response stream * @throws Exception */ public static byte[] post(String uri, final byte[] data, final String inputType, int expectedStatus, String expectedResultType, boolean printStream, int timeout, Credentials credentials) throws IOException { RequestEntity requestEntity = new RequestEntity() { public boolean isRepeatable() { return true; } public void writeRequest(OutputStream out) throws IOException { if (data != null) { out.write(data); } } public long getContentLength() { if (data != null) { return data.length; } return 0; } public String getContentType() { return inputType; } }; return post(uri, requestEntity, expectedStatus, expectedResultType, printStream, timeout, credentials); }
From source file:org.eclipse.net4j.http.tests.HTTPTest.java
/** * Result: With the current implementation (HttpClient / Jetty) it's not possible to transfer request data before */// w w w . j a v a 2 s . co m public void _testRequestFlush() throws Exception { HttpClient client = new HttpClient(); PostMethod method = new PostMethod("http://eike@localhost:8080/net4j/echotest"); //$NON-NLS-1$ method.setRequestEntity(new RequestEntity() { public long getContentLength() { return -1; } public String getContentType() { return "application/octet-stream"; //$NON-NLS-1$ } public boolean isRepeatable() { return false; } public void writeRequest(OutputStream out) throws IOException { int count = 10; out.write(count); for (int i = 0; i < count; i++) { send(out, i); } } private void send(OutputStream out, int b) throws IOException { try { msg("Writing " + b); //$NON-NLS-1$ out.write(b); out.flush(); Thread.sleep(1000); } catch (InterruptedException ex) { throw WrappedException.wrap(ex); } } }); client.executeMethod(method); InputStream responseBody = method.getResponseBodyAsStream(); @SuppressWarnings("resource") ExtendedDataInputStream in = new ExtendedDataInputStream(responseBody); int count = in.readInt(); for (int i = 0; i < count; i++) { int b = in.readByte(); assertEquals(i, b); long gap = in.readLong(); msg("Gap: " + gap); //$NON-NLS-1$ } method.releaseConnection(); }
From source file:org.geotools.data.wfs.protocol.http.DefaultHTTPProtocol.java
public HTTPResponse issuePost(final URL targetUrl, final POSTCallBack callback) throws IOException { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.finest("About to issue POST request to " + targetUrl.toExternalForm()); }//from w ww. j av a 2 s. c o m final String uri = targetUrl.toExternalForm(); final PostMethod postRequest = new PostMethod(uri); final RequestEntity requestEntity = new RequestEntity() { public long getContentLength() { return callback.getContentLength(); } public String getContentType() { return callback.getContentType(); } public boolean isRepeatable() { return false; } public void writeRequest(OutputStream out) throws IOException { callback.writeBody(out); } }; postRequest.setRequestEntity(requestEntity); HTTPResponse httpResponse = issueRequest(postRequest); return httpResponse; }
From source file:org.openrdf.http.client.HTTPClient.java
public void sendTransaction(final Iterable<? extends TransactionOperation> txn) throws IOException, RepositoryException, UnauthorizedException { checkRepositoryURL();//from ww w .ja va2s . c o m PostMethod method = new PostMethod(Protocol.getStatementsLocation(getRepositoryURL())); setDoAuthentication(method); // Create a RequestEntity for the transaction data method.setRequestEntity(new RequestEntity() { public long getContentLength() { return -1; // don't know } public String getContentType() { return Protocol.TXN_MIME_TYPE; } public boolean isRepeatable() { return true; } public void writeRequest(OutputStream out) throws IOException { TransactionWriter txnWriter = new TransactionWriter(); txnWriter.serialize(txn, out); } }); try { int httpCode = httpClient.executeMethod(method); if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new UnauthorizedException(); } else if (!is2xx(httpCode)) { ErrorInfo errInfo = getErrorInfo(method); throw new RepositoryException("Transaction failed: " + errInfo + " (" + httpCode + ")"); } } finally { releaseConnection(method); } }
From source file:org.openrdf.http.client.HTTPClient.java
public void upload(final Reader contents, String baseURI, final RDFFormat dataFormat, boolean overwrite, Resource... contexts)// w w w . ja v a2 s .c om throws IOException, RDFParseException, RepositoryException, UnauthorizedException { final Charset charset = dataFormat.hasCharset() ? dataFormat.getCharset() : Charset.forName("UTF-8"); RequestEntity entity = new RequestEntity() { public long getContentLength() { return -1; // don't know } public String getContentType() { return dataFormat.getDefaultMIMEType() + "; charset=" + charset.name(); } public boolean isRepeatable() { return false; } public void writeRequest(OutputStream out) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(out, charset); IOUtil.transfer(contents, writer); writer.flush(); } }; upload(entity, baseURI, overwrite, contexts); }
From source file:smartrics.rest.client.RestClientImpl.java
/** * Configures the instance of HttpMethod with the data in the request and * the host address./* w w w . java 2 s .com*/ * * @param m * the method class to configure * @param hostAddr * the host address * @param request * the rest request */ protected void configureHttpMethod(HttpMethod m, String hostAddr, final RestRequest request) { addHeaders(m, request); setUri(m, hostAddr, request); m.setQueryString(request.getQuery()); if (m instanceof EntityEnclosingMethod) { RequestEntity requestEntity = null; String fileName = request.getFileName(); if (fileName != null) { requestEntity = configureFileUpload(fileName); } else { fileName = request.getMultipartFileName(); if (fileName != null) { requestEntity = configureMultipartFileUpload(m, request, requestEntity, fileName); } else { requestEntity = new RequestEntity() { public boolean isRepeatable() { return true; } public void writeRequest(OutputStream out) throws IOException { PrintWriter printer = new PrintWriter(out); printer.print(request.getBody()); printer.flush(); } public long getContentLength() { return request.getBody().getBytes().length; } public String getContentType() { List<smartrics.rest.client.RestData.Header> values = request.getHeader("Content-Type"); String v = "text/xml"; if (values.size() != 0) v = values.get(0).getValue(); return v; } }; } } ((EntityEnclosingMethod) m).setRequestEntity(requestEntity); } }