List of usage examples for org.apache.commons.httpclient.methods InputStreamRequestEntity InputStreamRequestEntity
public InputStreamRequestEntity(InputStream paramInputStream, String paramString)
From source file:UnbufferedPost.java
public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("Usage: ChunkEncodedPost <file>"); System.out.println("<file> - full path to a file to be posted"); System.exit(1);/*from w w w. ja va 2 s .com*/ } HttpClient client = new HttpClient(); PostMethod httppost = new PostMethod("http://localhost:8080/httpclienttest/body"); File file = new File(args[0]); httppost.setRequestEntity(new InputStreamRequestEntity(new FileInputStream(file), file.length())); try { client.executeMethod(httppost); if (httppost.getStatusCode() == HttpStatus.SC_OK) { System.out.println(httppost.getResponseBodyAsString()); } else { System.out.println("Unexpected failure: " + httppost.getStatusLine().toString()); } } finally { httppost.releaseConnection(); } }
From source file:com.testmax.util.HttpUtil.java
public String postRequest(String url, String param, String xml) { String resp = ""; PostMethod post = new PostMethod(url); if (param.equalsIgnoreCase("body")) { //xmlData=urlConf.getUrlParamValue(param); byte buf[] = xml.getBytes(); ByteArrayInputStream in = new ByteArrayInputStream(buf); post.setRequestEntity(new InputStreamRequestEntity(new BufferedInputStream(in), xml.length())); } else {//from w w w.j a v a 2s . c o m post.setRequestHeader(param, xml); } post.setRequestHeader("Content-type", "text/xml; charset=utf-8"); // Get HTTP client org.apache.commons.httpclient.HttpClient httpsclient = new org.apache.commons.httpclient.HttpClient(); // Execute request try { int response = -1; try { response = httpsclient.executeMethod(post); resp = post.getResponseBodyAsString(); Header[] heads = post.getResponseHeaders(); String header = ""; for (Header head : heads) { header += head.getName() + ":" + head.getValue(); } System.out.println("Header=" + header); WmLog.printMessage("Response: " + resp); WmLog.printMessage("Response Header: " + header); } catch (HttpException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } finally { // Release current connection to the connection pool // once you are done post.releaseConnection(); } return resp; }
From source file:eu.learnpad.rest.utils.internal.DefaultRestUtils.java
@Override public boolean putPage(String spaceName, String pageName, InputStream pageXML) { HttpClient httpClient = getClient(); String uri = REST_URI + "/wikis/xwiki/spaces/" + spaceName + "/pages/" + pageName; PutMethod putMethod = new PutMethod(uri); putMethod.addRequestHeader("Accept", "application/xml"); putMethod.addRequestHeader("Accept-Ranges", "bytes"); RequestEntity pageRequestEntity = new InputStreamRequestEntity(pageXML, "application/xml"); putMethod.setRequestEntity(pageRequestEntity); try {/* www .j av a 2 s. c o m*/ httpClient.executeMethod(putMethod); return true; } catch (HttpException e) { logger.error("Unable to process the PUT request on page '" + spaceName + "." + pageName + "'.", e); return false; } catch (IOException e) { logger.error("Unable to PUT the page '" + spaceName + "." + pageName + "'.", e); return false; } }
From source file:edu.wfu.inotado.helper.RestClientHelper.java
/** * //from w w w . j a va 2 s. c om * * @param strURL * @param xml * @return */ public String postXml(String strURL, String xml) { // either get the previously stored post or create a new one PostMethod post = this.postHolder.get() != null ? this.postHolder.get() : new PostMethod(strURL); InputStream xmlStream = null; String responseStr = null; try { xmlStream = new ByteArrayInputStream(xml.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { log.error("Unsupport encoding for string: " + xml); } try { post.setRequestEntity(new InputStreamRequestEntity(xmlStream, xml.length())); post.addRequestHeader("Content-type", "text/xml; charset=ISO-8859-1"); HttpClient httpclient = new HttpClient(); int result = httpclient.executeMethod(post); log.debug("Response status code: " + result); log.debug("Response body: "); responseStr = convertStreamToString(post.getResponseBodyAsStream()); log.debug(responseStr); } catch (IOException e) { log.error("error occurred.", e); } finally { post.releaseConnection(); // clean up the holder postHolder.remove(); } return responseStr; }
From source file:eu.learnpad.core.rest.XWikiRestUtils.java
public boolean putPage(String wikiName, String spaceName, String pageName, InputStream pageXML) { HttpClient httpClient = restResource.getClient(); String uri = String.format("%s/wikis/%s/spaces/%s/pages/%s", DefaultRestResource.REST_URI, wikiName, spaceName, pageName);/* w ww. j a v a 2s. com*/ PutMethod putMethod = new PutMethod(uri); putMethod.addRequestHeader("Accept", "application/xml"); putMethod.addRequestHeader("Accept-Ranges", "bytes"); RequestEntity pageRequestEntity = new InputStreamRequestEntity(pageXML, "application/xml"); putMethod.setRequestEntity(pageRequestEntity); try { httpClient.executeMethod(putMethod); return true; } catch (HttpException e) { String message = String.format("Unable to process the PUT request on page '%s:%s.%s'.", wikiName, spaceName, pageName); logger.error(message, e); return false; } catch (IOException e) { String message = String.format("Unable to PUT the page '%s:%s.%s'.", wikiName, spaceName, pageName); logger.error(message, e); return false; } }
From source file:com.testmax.uri.HttpRestWithXmlBody.java
public String handleHTTPPostUnit() { String xmlData = ""; String resp = ""; // Get target URL String strURL = this.url; URLConfig urlConf = this.page.getURLConfig(); // Prepare HTTP post PostMethod post = new PostMethod(strURL); // Request content will be retrieved directly // from the input stream // Per default, the request content needs to be buffered // in order to determine its length. // Request body buffering can be avoided when // content length is explicitly specified // Specify content type and encoding // If content encoding is not explicitly specified // ISO-8859-1 is assumed Set<String> s = urlConf.getUrlParamset(); for (String param : s) { xmlData = urlConf.getUrlParamValue(param); if (param.equalsIgnoreCase("body")) { //xmlData=urlConf.getUrlParamValue(param); byte buf[] = xmlData.getBytes(); ByteArrayInputStream in = new ByteArrayInputStream(buf); post.setRequestEntity(new InputStreamRequestEntity(new BufferedInputStream(in), xmlData.length())); } else {/*from w w w .j a va 2s.c o m*/ post.setRequestHeader(param, xmlData); } WmLog.printMessage(">>> Setting URL Param " + param + "=" + xmlData); } // Get HTTP client org.apache.commons.httpclient.HttpClient httpsclient = new org.apache.commons.httpclient.HttpClient(); // Execute request try { int response = -1; //set the time for this HTTP request this.startRecording(); long starttime = this.getCurrentTime(); try { response = httpsclient.executeMethod(post); resp = post.getResponseBodyAsString(); Header[] heads = post.getResponseHeaders(); this.cookies = httpsclient.getState().getCookies(); String header = ""; for (Header head : heads) { header += head.getName() + ":" + head.getValue(); } System.out.println("Header=" + header); } catch (HttpException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Measure the time passed between response long elaspedTime = this.getElaspedTime(starttime); this.stopRecording(response, elaspedTime); System.out.println(resp); System.out.println("ElaspedTime: " + elaspedTime); WmLog.printMessage("Response XML: " + resp); WmLog.printMessage("ElaspedTime: " + elaspedTime); this.printRecording(); this.printLog(); if (response == 200 || response == 400) { this.addThreadActionMonitor(this.action, true, elaspedTime); } else { this.addThreadActionMonitor(this.action, false, elaspedTime); WmLog.printMessage("Input XML: " + xmlData); WmLog.printMessage("Response XML: " + resp); } if (resp.contains("{") && resp.contains("}") && resp.contains(":")) { try { resp = "{ \"root\": " + resp + "}"; HierarchicalStreamCopier copier = new HierarchicalStreamCopier(); HierarchicalStreamDriver jsonXmlDriver = new JettisonMappedXmlDriver(); StringWriter strWriter = new StringWriter(); copier.copy(jsonXmlDriver.createReader(new StringReader(resp)), new PrettyPrintWriter(strWriter)); resp = strWriter.toString(); System.out.println(resp); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } finally { // Release current connection to the connection pool // once you are done post.releaseConnection(); } return resp; }
From source file:com.epam.wilma.test.client.HttpRequestSender.java
/** * Sends a new HTTP request to a server through a proxy. * @param requestParameters a set of parameters that will set the content of the request * and specify the proxy it should go through *///from w ww .j av a 2 s . c o m public void callWilmaTestServer(final RequestParameters requestParameters, final TestClientParameters clientParameters) { try { HttpClient httpClient = new HttpClient(); String serverUrl = requestParameters.getTestServerUrl(); logger.info("Server URL: " + serverUrl); PostMethod httpPost = new PostMethod(serverUrl); if (clientParameters.isUseProxy()) { String proxyHost = requestParameters.getWilmaHost(); Integer proxyPort = requestParameters.getWilmaPort(); logger.info("Proxy: " + proxyHost + ":" + proxyPort); httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort); } InputStream inputStream = requestParameters.getInputStream(); if (requestParameters.getContentType().contains("fastinfoset")) { logger.info("Compressing it by using FIS."); inputStream = compress(inputStream); } if (requestParameters.getContentEncoding().contains("gzip")) { logger.info("Encoding it by using gzip."); inputStream = encode(inputStream); httpPost.setRequestHeader("Content-Encoding", requestParameters.getContentEncoding()); } InputStreamRequestEntity entity = new InputStreamRequestEntity(inputStream, requestParameters.getContentType()); httpPost.setRequestEntity(entity); String acceptHeader = requestParameters.getAcceptHeader(); logger.info("Accept (header): " + acceptHeader); httpPost.setRequestHeader("Accept", acceptHeader); String acceptEncoding = requestParameters.getAcceptEncoding(); logger.info("Accept-Encoding: " + acceptEncoding); httpPost.addRequestHeader("Accept-Encoding", acceptEncoding); logger.info("Add 'AlterMessage' header."); httpPost.addRequestHeader("AlterMessage", "true"); //always request alter message from Wilma //httpPost.addRequestHeader("0", "WilmaBypass=true"); httpClient.getHttpConnectionManager().getParams() .setSendBufferSize(clientParameters.getRequestBufferSize()); httpClient.getHttpConnectionManager().getParams() .setReceiveBufferSize(clientParameters.getResponseBufferSize()); int statusCode = httpClient.executeMethod(httpPost); logger.info("Response Status Code: " + statusCode); if (clientParameters.getAllowResponseLogging()) { logger.info(getInputStreamAsString(httpPost.getResponseBodyAsStream())); } } catch (UnsupportedEncodingException e) { throw new SystemException("Unsupported encoding.", e); } catch (HttpException e) { throw new SystemException("Http exception occurred.", e); } catch (IOException e) { throw new SystemException("InputStream cannot be read.", e); } }
From source file:com.wfreitas.camelsoap.SoapClient.java
public String sendRequest(String address, String message, String action) throws Exception { String responseBodyAsString;// w ww .ja v a 2 s. co m PostMethod postMethod = new PostMethod(address); try { HttpClient client = new HttpClient(); postMethod.setRequestHeader("SOAPAction", action); postMethod.setRequestEntity( new InputStreamRequestEntity(new ByteArrayInputStream(message.getBytes("UTF-8")), "text/xml") ); client.executeMethod(postMethod); responseBodyAsString = postMethod.getResponseBodyAsString(); } finally { postMethod.releaseConnection(); } return responseBodyAsString; }
From source file:edu.unc.lib.dl.admin.controller.IngestController.java
@RequestMapping(value = "ingest/{pid}", method = RequestMethod.POST) public @ResponseBody Map<String, ? extends Object> ingestPackageController(@PathVariable("pid") String pid, @RequestParam("type") String type, @RequestParam(value = "name", required = false) String name, @RequestParam("file") MultipartFile ingestFile, HttpServletRequest request, HttpServletResponse response) {// ww w . j a v a 2 s. co m String destinationUrl = swordUrl + "collection/" + pid; HttpClient client = HttpClientUtil.getAuthenticatedClient(destinationUrl, swordUsername, swordPassword); client.getParams().setAuthenticationPreemptive(true); PostMethod method = new PostMethod(destinationUrl); // Set SWORD related headers for performing ingest method.addRequestHeader(HttpClientUtil.FORWARDED_GROUPS_HEADER, GroupsThreadStore.getGroupString()); method.addRequestHeader("Packaging", type); method.addRequestHeader("On-Behalf-Of", GroupsThreadStore.getUsername()); method.addRequestHeader("Content-Type", ingestFile.getContentType()); method.addRequestHeader("Content-Length", Long.toString(ingestFile.getSize())); method.addRequestHeader("mail", request.getHeader("mail")); method.addRequestHeader("Content-Disposition", "attachment; filename=" + ingestFile.getOriginalFilename()); if (name != null && name.trim().length() > 0) method.addRequestHeader("Slug", name); // Setup the json response Map<String, Object> result = new HashMap<String, Object>(); result.put("action", "ingest"); result.put("destination", pid); try { method.setRequestEntity( new InputStreamRequestEntity(ingestFile.getInputStream(), ingestFile.getSize())); client.executeMethod(method); response.setStatus(method.getStatusCode()); // Object successfully "create", or at least queued if (method.getStatusCode() == 201) { Header location = method.getResponseHeader("Location"); String newPid = location.getValue(); newPid = newPid.substring(newPid.lastIndexOf('/')); result.put("pid", newPid); } else if (method.getStatusCode() == 401) { // Unauthorized result.put("error", "Not authorized to ingest to container " + pid); } else if (method.getStatusCode() == 400 || method.getStatusCode() >= 500) { // Server error, report it to the client result.put("error", "A server error occurred while attempting to ingest \"" + ingestFile.getName() + "\" to " + pid); // Inspect the SWORD response, extracting the stacktrace InputStream entryPart = method.getResponseBodyAsStream(); Abdera abdera = new Abdera(); Parser parser = abdera.getParser(); Document<Entry> entryDoc = parser.parse(entryPart); Object rootEntry = entryDoc.getRoot(); String stackTrace; if (rootEntry instanceof FOMExtensibleElement) { stackTrace = ((org.apache.abdera.parser.stax.FOMExtensibleElement) entryDoc.getRoot()) .getExtension(SWORD_VERBOSE_DESCRIPTION).getText(); result.put("errorStack", stackTrace); } else { stackTrace = ((Entry) rootEntry).getExtension(SWORD_VERBOSE_DESCRIPTION).getText(); result.put("errorStack", stackTrace); } log.warn("Failed to upload ingest package file " + ingestFile.getName() + " from user " + GroupsThreadStore.getUsername(), stackTrace); } return result; } catch (Exception e) { log.warn("Encountered an unexpected error while ingesting package " + ingestFile.getName() + " from user " + GroupsThreadStore.getUsername(), e); result.put("error", "A server error occurred while attempting to ingest \"" + ingestFile.getName() + "\" to " + pid); return result; } finally { method.releaseConnection(); try { ingestFile.getInputStream().close(); } catch (IOException e) { log.warn("Failed to close ingest package file", e); } } }
From source file:com.zimbra.cs.dav.service.DavMethod.java
public HttpMethod toHttpMethod(DavContext ctxt, String targetUrl) throws IOException, DavException { if (ctxt.getUpload() != null && ctxt.getUpload().getSize() > 0) { PostMethod method = new PostMethod(targetUrl) { @Override//w w w . j av a 2s .com public String getName() { return getMethodName(); } }; RequestEntity reqEntry; if (ctxt.hasRequestMessage()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); XMLWriter writer = new XMLWriter(baos); writer.write(ctxt.getRequestMessage()); reqEntry = new ByteArrayRequestEntity(baos.toByteArray()); } else { // this could be a huge upload reqEntry = new InputStreamRequestEntity(ctxt.getUpload().getInputStream(), ctxt.getUpload().getSize()); } method.setRequestEntity(reqEntry); return method; } return new GetMethod(targetUrl) { @Override public String getName() { return getMethodName(); } }; }