List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestEntity
public void setRequestEntity(RequestEntity paramRequestEntity)
From source file:com.comcast.cats.jenkins.service.AbstractService.java
/** * Create Project Via GET//from w w w .j av a 2 s. c o m * * @param requestUrl * Relative request URL * @param mapperClass * Class to which the response should cast to. * @return JAXB deserialized response */ protected Object createProject(final String requestUrl, Class<?> mapperClass, File config) { Object domainObject = null; HttpClient client = new HttpClient(); try { PostMethod request = new PostMethod(getAbsoluteUrl(requestUrl)); request.addRequestHeader(CONTENT_TYPE, APPLICATION_XML); RequestEntity entity = new FileRequestEntity(config, "text/xml; charset=UTF-8"); request.setRequestEntity(entity); String apiToken = jenkinsClientProperties.getJenkinsApiToken(); if (!apiToken.isEmpty()) { request.setDoAuthentication(true); } domainObject = sendRequestToJenkins(mapperClass, domainObject, client, request, apiToken); } catch (Exception e) { LOGGER.error(e.getMessage()); } return domainObject; }
From source file:be.fedict.trust.ocsp.OnlineOcspRepository.java
private OCSPResp getOcspResponse(URI ocspUri, X509Certificate certificate, X509Certificate issuerCertificate) throws OCSPException, IOException { LOG.debug("OCSP URI: " + ocspUri); OCSPReqGenerator ocspReqGenerator = new OCSPReqGenerator(); CertificateID certId = new CertificateID(CertificateID.HASH_SHA1, issuerCertificate, certificate.getSerialNumber()); ocspReqGenerator.addRequest(certId); OCSPReq ocspReq = ocspReqGenerator.generate(); byte[] ocspReqData = ocspReq.getEncoded(); PostMethod postMethod = new PostMethod(ocspUri.toString()); RequestEntity requestEntity = new ByteArrayRequestEntity(ocspReqData, "application/ocsp-request"); postMethod.addRequestHeader("User-Agent", "jTrust OCSP Client"); postMethod.setRequestEntity(requestEntity); HttpClient httpClient = new HttpClient(); if (null != this.networkConfig) { httpClient.getHostConfiguration().setProxy(this.networkConfig.getProxyHost(), this.networkConfig.getProxyPort()); }//from w w w .j a v a 2 s. c o m if (null != this.credentials) { HttpState httpState = httpClient.getState(); this.credentials.init(httpState); } int responseCode; try { httpClient.executeMethod(postMethod); responseCode = postMethod.getStatusCode(); } catch (ConnectException e) { LOG.debug("OCSP responder is down"); return null; } if (HttpURLConnection.HTTP_OK != responseCode) { LOG.error("HTTP response code: " + responseCode); return null; } Header responseContentTypeHeader = postMethod.getResponseHeader("Content-Type"); if (null == responseContentTypeHeader) { LOG.debug("no Content-Type response header"); return null; } String resultContentType = responseContentTypeHeader.getValue(); if (!"application/ocsp-response".equals(resultContentType)) { LOG.debug("result content type not application/ocsp-response"); return null; } Header responseContentLengthHeader = postMethod.getResponseHeader("Content-Length"); if (null != responseContentLengthHeader) { String resultContentLength = responseContentLengthHeader.getValue(); if ("0".equals(resultContentLength)) { LOG.debug("no content returned"); return null; } } OCSPResp ocspResp = new OCSPResp(postMethod.getResponseBodyAsStream()); LOG.debug("OCSP response size: " + ocspResp.getEncoded().length + " bytes"); return ocspResp; }
From source file:com.legstar.test.cixs.AbstractHttpClientTester.java
/** * Perform a request/reply using byte[] application/octet-stream as payload. * //from w w w . j a v a2 s . co m * @param url the target url * @param bytesRequest the bytes request * @return the bytes reply * @throws Exception if something goes wrong */ public byte[] postBytes(final String url, final byte[] bytesRequest) throws Exception { PostMethod postMethod = new PostMethod(url); ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(bytesRequest, "application/octet-stream"); postMethod.setRequestEntity(requestEntity); int rc = HTTPCLIENT.executeMethod(postMethod); assertEquals(postMethod.getStatusText(), 200, rc); byte[] bytesReply = postMethod.getResponseBody(); postMethod.releaseConnection(); return bytesReply; }
From source file:com.nokia.helium.diamonds.DiamondsClient.java
private PostMethod getPostMethod(String fileName, String urlPath) { // Get the Diamonds XML-file which is to be exported File input = new File(fileName); // Prepare HTTP post PostMethod post = new PostMethod(urlPath); // Request content will be retrieved directly // from the input stream RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1"); post.setRequestEntity(entity); return post;//from w w w . ja va 2 s . c om }
From source file:jp.co.cyberagent.jenkins.plugins.AndroidAppZonePublisher.java
@Override public boolean perform(final AbstractBuild build, final Launcher launcher, final BuildListener listener) { StringBuilder changeLog = new StringBuilder(); for (Object changeObject : build.getChangeSet().getItems()) { ChangeLogSet.Entry change = (ChangeLogSet.Entry) changeObject; if (changeLog.length() > 0) { changeLog.append("\n"); }// w ww. j a va 2 s. c o m changeLog.append(change.getMsg() + " (" + change.getAuthor().getDisplayName() + ")"); } String server = getDescriptor().getServer(); if (server == null || server.length() == 0) { listener.getLogger().println(TAG + "AppZone server not set. Please set in global config! Aborting."); return false; } List<FilePath> files = getPossibleAppFiles(build, listener); if (files.isEmpty()) { listener.getLogger().println(TAG + "No file to publish found. Skip."); return true; } Iterator<FilePath> fileIterator = files.iterator(); while (fileIterator.hasNext()) { try { FilePath file = fileIterator.next(); String fileName = file.getName(); DeployStrategy deploy; listener.getLogger().println(TAG + "File: " + fileName); if (fileName.endsWith(".apk")) { deploy = new DeployStrategyAndroid(server, id, tag, prependNameToTag, file, build, listener); } else if (fileName.endsWith(".ipa")) { deploy = new DeployStrategyIOs(server, id, tag, prependNameToTag, file, build, listener); } else { return false; } deploy.setApiKey(getDescriptor().getApikey()); deploy.setChangeLog(changeLog.toString()); listener.getLogger().println(TAG + "Version: " + deploy.getVersion()); listener.getLogger().println(TAG + "Publishing to: " + deploy.getUrl()); setUpSsl(); HttpClient httpclient = new HttpClient(); PostMethod filePost = new PostMethod(deploy.getUrl()); List<Part> parts = deploy.getParts(); filePost.setRequestEntity( new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), filePost.getParams())); httpclient.executeMethod(filePost); int statusCode = filePost.getStatusCode(); if (statusCode < 200 || statusCode > 299) { String body = filePost.getResponseBodyAsString(); listener.getLogger().println(TAG + "Response (" + statusCode + "):" + body); return false; } } catch (IOException e) { listener.getLogger().print(e.getMessage()); return false; } } return true; }
From source file:net.morphbank.webclient.PostXML.java
public void post(String strURL, String strXMLFilename) throws Exception { File input = new File(strXMLFilename); // Prepare HTTP post PostMethod post = new PostMethod(strURL); // Request content will be retrieved directly // from the input stream Part[] parts = { Part[] parts = { new FilePart("uploadFile", strXMLFilename, input) }; RequestEntity entity = new MultipartRequestEntity(parts, post.getParams()); // RequestEntity entity = new FileRequestEntity(input, // "text/xml;charset=utf-8"); post.setRequestEntity(entity); // Get HTTP client HttpClient httpclient = new HttpClient(); // Execute request try {//from www.j a v a 2 s . c om System.out.println("Trying post"); int result = httpclient.executeMethod(post); // Display status code System.out.println("Response status code: " + result); // Display response System.out.println("Response body: "); InputStream response = post.getResponseBodyAsStream(); //int j = response.read(); System.out.write(j); for (int i = response.read(); i != -1; i = response.read()) { System.out.write(i); } //System.out.flush(); } finally { // Release current connection to the connection pool once you are // done post.releaseConnection(); } }
From source file:com.moss.jaxwslite.Service.java
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (args == null) { args = new Object[0]; }/*from w w w .ja va 2 s. c o m*/ if (method.getName().equals("toString") && args.length == 0) { return url.toString(); } PostMethod post = new PostMethod(url.toString()); final byte[] requestContent = type.request(method, args); RequestEntity requestEntity = new ByteArrayRequestEntity(requestContent); post.setRequestEntity(requestEntity); post.addRequestHeader("Content-Type", "text/xml"); if (log.isDebugEnabled()) { new Thread() { public void run() { try { setPriority(MIN_PRIORITY); ByteArrayOutputStream out = new ByteArrayOutputStream(); JAXBHelper.beautify(new ByteArrayInputStream(requestContent), out); StringBuilder sb = new StringBuilder(); sb.append("Sending post: ").append(url).append("\n"); sb.append(new String(out.toByteArray())); log.debug(sb.toString()); } catch (Exception e) { throw new RuntimeException(e); } } }.start(); } try { int responseCode = client.executeMethod(post); boolean fault = responseCode != 200; final byte[] responseContent; { InputStream in = post.getResponseBodyAsStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[1024 * 10]; //10k buffer for (int numRead = in.read(buffer); numRead != -1; numRead = in.read(buffer)) { out.write(buffer, 0, numRead); } responseContent = out.toByteArray(); } if (log.isDebugEnabled()) { new Thread() { public void run() { try { setPriority(MIN_PRIORITY); ByteArrayOutputStream out = new ByteArrayOutputStream(); JAXBHelper.beautify(new ByteArrayInputStream(responseContent), out); StringBuilder sb = new StringBuilder(); sb.append("Receiving post response: ").append(url).append("\n"); sb.append(new String(out.toByteArray())); log.debug(sb.toString()); } catch (Exception e) { throw new RuntimeException(e); } } }.start(); } Object response = type.response(method, responseContent, fault); if (response instanceof Exception) { throw (Exception) response; } else { return response; } } finally { post.releaseConnection(); } }
From source file:com.sun.faban.harness.util.DeployTask.java
/** * Executes the Faban deployment task.//from w ww . j av a 2s . c om * @throws BuildException If there is an */ public void execute() throws BuildException { try { // First check the jar file and name if (jarFile == null) throw new BuildException("jar attribute missing for target deploy."); if (!jarFile.isFile()) throw new BuildException("jar file not found."); String jarName = jarFile.getName(); if (!jarName.endsWith(".jar")) throw new BuildException("Jar file name must end with \".jar\""); jarName = jarName.substring(0, jarName.length() - 4); if (jarName.indexOf('.') > -1) throw new BuildException("Jar file name must not have any " + "dots except ending with \".jar\""); // Prepare the parts for the request. ArrayList<Part> params = new ArrayList<Part>(4); if (user != null) params.add(new StringPart("user", user)); if (password != null) params.add(new StringPart("password", password)); if (clearConfig) params.add(new StringPart("clearconfig", "true")); params.add(new FilePart("jarfile", jarFile)); Part[] parts = new Part[params.size()]; parts = params.toArray(parts); // Prepare the post method. PostMethod post = new PostMethod(target + "/deploy"); // Ensure text/plain is the only accept header. post.removeRequestHeader("Accept"); post.setRequestHeader("Accept", "text/plain"); post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); // Execute the multi-part post method. HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); int status = client.executeMethod(post); StringBuilder b = new StringBuilder(); InputStream respBody = post.getResponseBodyAsStream(); byte[] readBuffer = new byte[8192]; for (;;) { int size = respBody.read(readBuffer); if (size == -1) break; b.append(new String(readBuffer, 0, size)); } String response = b.toString(); // Check status. if (status == HttpStatus.SC_CONFLICT) { handleErrorFlush(response); throw new BuildException( "Benchmark to deploy is currently " + "run or queued to be run. Please clear run queue " + "of this benchmark before deployment"); } else if (status == HttpStatus.SC_NOT_ACCEPTABLE) { handleErrorFlush(response); throw new BuildException( "Benchmark deploy name or deploy " + "file invalid. Deploy file may contain errors. Name " + "must have no '.' and file must have the " + "'.jar' extensions."); } else if (status != HttpStatus.SC_CREATED) { handleOutput(response); throw new BuildException( "Faban responded with status code " + status + ". Status code 201 (SC_CREATED) expected."); } } catch (FileNotFoundException e) { throw new BuildException(e); } catch (HttpException e) { throw new BuildException(e); } catch (IOException e) { throw new BuildException(e); } }
From source file:com.ziaconsulting.zoho.EditorController.java
@Override protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) { Match match = req.getServiceMatch(); Map<String, String> vars = match.getTemplateVars(); NodeRef theNodeRef = new NodeRef(vars.get("store_type"), vars.get("store_id"), vars.get("id")); String fileName = serviceRegistry.getNodeService().getProperty(theNodeRef, ContentModel.PROP_NAME) .toString();//from w w w .j a v a2 s . c o m String protocol = ssl ? "https" : "http"; String extension; if (fileName.lastIndexOf('.') != -1) { extension = fileName.substring(fileName.lastIndexOf('.') + 1); } else { String contentMime = serviceRegistry.getContentService() .getReader(theNodeRef, ContentModel.PROP_CONTENT).getMimetype(); extension = serviceRegistry.getMimetypeService().getExtensionsByMimetype().get(contentMime); // Attach this extension to the filename fileName += "." + extension; log.debug("Extension not found, using mimetype " + contentMime + " to guess the extension file name is now " + fileName); } String zohoUrl = ""; if (Arrays.binarySearch(zohoDocFileExtensions, extension) >= 0) { zohoUrl = writerUrl; } else if (Arrays.binarySearch(zohoXlsFileExtensions, extension) >= 0) { zohoUrl = sheetUrl; } else if (Arrays.binarySearch(zohoPptFileExtensions, extension) >= 0) { zohoUrl = showUrl; } else { log.info("Invalid extension " + extension); return getErrorMap("Invalid extension"); } // Create multipart form for post List<Part> parts = new ArrayList<Part>(); String output = ""; if (vars.get("mode").equals("edit")) { output = "url"; parts.add(new StringPart("mode", "collabedit")); } else if (vars.get("mode").equals("view")) { output = "viewurl"; parts.add(new StringPart("mode", "view")); } String docIdBase = vars.get("store_type") + vars.get("store_id") + vars.get("id"); parts.add(new StringPart("documentid", generateDocumentId(docIdBase))); String id = theNodeRef.toString() + "#" + serviceRegistry.getAuthenticationService().getCurrentTicket(); parts.add(new StringPart("id", id)); parts.add(new StringPart("format", extension)); parts.add(new StringPart("filename", fileName)); parts.add(new StringPart("username", serviceRegistry.getAuthenticationService().getCurrentUserName())); parts.add(new StringPart("skey", skey)); if (useRemoteAgent) { parts.add(new StringPart("agentname", remoteAgentName)); } else { String saveUrl; saveUrl = protocol + "://" + this.saveUrl + "/alfresco/s/zohosave"; parts.add(new StringPart("saveurl", saveUrl)); } ContentReader cr = serviceRegistry.getContentService().getReader(theNodeRef, ContentModel.PROP_CONTENT); if (!(cr instanceof FileContentReader)) { log.error("The content reader was not a FileContentReader"); return getErrorMap("Error"); } PartSource src = null; try { src = new FilePartSource(fileName, ((FileContentReader) cr).getFile()); } catch (FileNotFoundException e) { e.printStackTrace(); log.error("The content did not exist."); return getErrorMap("Error"); } parts.add(new FilePart("content", src, cr.getMimetype(), null)); HttpClient client = new HttpClient(); String zohoFormUrl = protocol + "://" + zohoUrl + "/remotedoc.im?" + "apikey=" + apiKey + "&output=" + output; PostMethod httppost = new PostMethod(zohoFormUrl); httppost.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[0]), httppost.getParams())); Map<String, Object> returnMap = getReturnMap(); String retStr = ""; int zohoStatus = 0; try { zohoStatus = client.executeMethod(httppost); retStr = httppost.getResponseBodyAsString(); } catch (HttpException he) { log.error("Error", he); returnMap = getErrorMap("Error"); } catch (IOException io) { io.printStackTrace(); log.error("Error", io); returnMap = getErrorMap("Error"); } if (zohoStatus == 200) { Map<String, String> parsedResponse = parseResponse(retStr); if (parsedResponse.containsKey("RESULT") && parsedResponse.get("RESULT").equals("TRUE")) { returnMap.put("zohourl", parsedResponse.get("URL")); } else if (parsedResponse.containsKey("RESULT") && parsedResponse.get("RESULT").equals("FALSE")) { returnMap = getErrorMap(parsedResponse.get("ERROR")); } } else { returnMap = getErrorMap("Remote server did not respond"); } return returnMap; }
From source file:au.edu.usq.fascinator.harvester.fedora.restclient.FedoraRestClient.java
private void addDatastream(String pid, String dsId, Properties options, String contentType, RequestEntity request) throws IOException { StringBuilder uri = new StringBuilder(getBaseUrl()); uri.append("/objects/"); uri.append(pid);/*w w w . j av a 2 s . c o m*/ uri.append("/datastreams/"); uri.append(dsId); addParam(uri, options, "controlGroup"); addParam(uri, options, "dsLocation"); addParam(uri, options, "altIDs"); addParam(uri, options, "dsLabel"); addParam(uri, options, "versionable"); addParam(uri, options, "dsState"); addParam(uri, options, "formatURI"); addParam(uri, options, "checksumType"); addParam(uri, options, "checksum"); addParam(uri, options, "logMessage"); PostMethod method = new PostMethod(uri.toString()); method.setRequestEntity(request); method.setRequestHeader("Content-Type", contentType); executeMethod(method); method.releaseConnection(); }