List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestEntity
public void setRequestEntity(RequestEntity paramRequestEntity)
From source file:cuanto.api.CuantoConnector.java
/** * Creates a new TestOutcome for the specified TestRun on the Cuanto server using the details provided. The ID value on * the testOutcome argument will be set upon successful creation. * * @param testOutcome The TestOutcome to be created on the Cuanto server. * @param testRun The TestRun to which the TestOutcome should be added. * @return The server-assigned ID of the TestOutcome. *//*w ww. j a v a2 s .com*/ public Long addTestOutcome(TestOutcome testOutcome, TestRun testRun) { PostMethod post = (PostMethod) getHttpMethod(HTTP_POST, getCuantoUrl() + "/api/addTestOutcome"); try { testOutcome.setTestRun(testRun); testOutcome.setProjectKey(this.projectKey); post.setRequestEntity(new StringRequestEntity(testOutcome.toJSON(), "application/json", null)); int httpStatus = getHttpClient().executeMethod(post); if (httpStatus == HttpStatus.SC_CREATED) { TestOutcome fetchedOutcome = TestOutcome.fromJSON(getResponseBodyAsString(post)); testOutcome.setId(fetchedOutcome.getId()); testOutcome.getTestCase().setId(fetchedOutcome.getTestCase().getId()); return fetchedOutcome.getId(); } else { throw new RuntimeException("Adding the TestOutcome failed with HTTP status code " + httpStatus + ": \n" + getResponseBodyAsString(post)); } } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } catch (ParseException e) { throw new RuntimeException("Error parsing server response", e); } }
From source file:com.denimgroup.threadfix.remote.HttpRestUtils.java
@Nonnull public <T> RestResponse<T> httpPostFile(@Nonnull String path, @Nonnull File file, @Nonnull String[] paramNames, @Nonnull String[] paramVals, @Nonnull Class<T> targetClass) { if (isUnsafeFlag()) Protocol.registerProtocol("https", new Protocol("https", new AcceptAllTrustFactory(), 443)); String completeUrl = makePostUrl(path); if (completeUrl == null) { LOGGER.debug("The POST url could not be generated. Aborting request."); return ResponseParser .getErrorResponse("The POST url could not be generated and the request was not attempted.", 0); }//from w ww .j a v a 2 s. c o m PostMethod filePost = new PostMethod(completeUrl); filePost.setRequestHeader("Accept", "application/json"); RestResponse<T> response = null; int status = -1; try { Part[] parts = new Part[paramNames.length + 2]; parts[paramNames.length] = new FilePart("file", file); parts[paramNames.length + 1] = new StringPart("apiKey", propertiesManager.getKey()); for (int i = 0; i < paramNames.length; i++) { parts[i] = new StringPart(paramNames[i], paramVals[i]); } filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); filePost.setContentChunked(true); HttpClient client = new HttpClient(); status = client.executeMethod(filePost); if (status != 200) { LOGGER.warn("Request for '" + completeUrl + "' status was " + status + ", not 200 as expected."); } if (status == 302) { Header location = filePost.getResponseHeader("Location"); printRedirectInformation(location); } response = ResponseParser.getRestResponse(filePost.getResponseBodyAsStream(), status, targetClass); } catch (SSLHandshakeException sslHandshakeException) { importCert(sslHandshakeException); } catch (IOException e1) { LOGGER.error("There was an error and the POST request was not finished.", e1); response = ResponseParser.getErrorResponse("There was an error and the POST request was not finished.", status); } return response; }
From source file:es.mityc.firmaJava.ts.TSCliente.java
/** * Este mtodo genera el Sello de Tiempo// w w w.j a v a2s .c o m * @param binarioaSellar fichero binario que se va a sellar * @return TimeStampToken en formato binario * @throws TSClienteError */ public byte[] generarSelloTiempo(byte[] binarioaSellar) throws TSClienteError { if (binarioaSellar == null) { log.error(MENSAJE_NO_DATOS_SELLO_TIEMPO); throw new TSClienteError(I18n.getResource(LIBRERIA_TSA_ERROR_1)); } else { log.info(MENSAJE_GENERANDO_SELLO_TIEMPO); TimeStampRequestGenerator generadorPeticion = new TimeStampRequestGenerator(); TimeStampRequest peticion = null; TimeStampResponse respuesta = null; try { MessageDigest resumen = MessageDigest.getInstance(algoritmoHash); resumen.update(binarioaSellar); peticion = generadorPeticion.generate(TSPAlgoritmos.getOID(algoritmoHash), resumen.digest()); log.info(MENSAJE_PETICION_TSA_GENERADA); } catch (Exception e) { log.error(MENSAJE_ERROR_PETICION_TSA); throw new TSClienteError(I18n.getResource(LIBRERIA_TSA_ERROR_10)); } cliente.getParams().setParameter(HttpClientParams.SO_TIMEOUT, INT5000); // Comprueba si hay configurado un proxy String servidorProxy = System.getProperty("http.proxyHost"); if (servidorProxy != null && !servidorProxy.trim().equals(CADENA_VACIA)) { int puertoProxy = 80; try { puertoProxy = Integer.parseInt(System.getProperty("http.proxyPort")); } catch (NumberFormatException ex) { } cliente.getHostConfiguration().setProxy(servidorProxy, puertoProxy); Credentials defaultcreds = new AuthenticatorProxyCredentials(servidorProxy, CADENA_VACIA); cliente.getState().setProxyCredentials(AuthScope.ANY, defaultcreds); } PostMethod metodo = new PostMethod(servidorTSA); metodo.addRequestHeader(CONTENT_TYPE, APPLICATION_TIMESTAMP_QUERY); ByteArrayInputStream datos = null; try { datos = new ByteArrayInputStream(peticion.getEncoded()); } catch (IOException e) { log.error(MENSAJE_ERROR_PETICION + e.getMessage()); throw new TSClienteError( I18n.getResource(LIBRERIA_TSA_ERROR_11) + DOS_PUNTOS_ESPACIO + e.getMessage()); } InputStreamRequestEntity rq = new InputStreamRequestEntity(datos); metodo.setRequestEntity(rq); metodo.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); byte[] cuerpoRespuesta = null; try { int estadoCodigo = cliente.executeMethod(metodo); log.info(MENSAJE_PETICION_TSA_ENVIADA); if (estadoCodigo != HttpStatus.SC_OK) { log.error(MENSAJE_FALLO_EJECUCION_METODO + metodo.getStatusLine()); throw new TSClienteError( I18n.getResource(LIBRERIA_TSA_ERROR_12) + DOS_PUNTOS_ESPACIO + metodo.getStatusLine()); } cuerpoRespuesta = metodo.getResponseBody(); log.info(MENSAJE_RESPUESTA_TSA_OBTENIDA); try { respuesta = new TimeStampResponse(cuerpoRespuesta); try { respuesta.validate(peticion); log.info(MENSAJE_RESPUESTA_TSA_VALIDADA_OK); // Para solucionar bug en libreria bouncycastle //return respuesta.getTimeStampToken().getEncoded(); //AppPerfect: Falso positivo ASN1InputStream is = new ASN1InputStream(cuerpoRespuesta); ASN1Sequence seq = ASN1Sequence.getInstance(is.readObject()); DEREncodable enc = seq.getObjectAt(1); if (enc == null) return null; return enc.getDERObject().getEncoded(); //Fin Para solucionar bug en libreria bouncycastle } catch (TSPException e) { log.error(MENSAJE_RESPUESTA_NO_VALIDA + e.getMessage()); throw new TSClienteError( I18n.getResource(LIBRERIA_TSA_ERROR_9) + DOS_PUNTOS_ESPACIO + e.getMessage()); } } catch (TSPException e) { log.error(MENSAJE_RESPUESTA_MAL_FORMADA + e.getMessage()); throw new TSClienteError( I18n.getResource(LIBRERIA_TSA_ERROR_8) + DOS_PUNTOS_ESPACIO + e.getMessage()); } catch (IOException e) { log.error(MENSAJE_SECUENCIA_BYTES_MAL_CODIFICADA + e.getMessage()); throw new TSClienteError( I18n.getResource(LIBRERIA_TSA_ERROR_7) + DOS_PUNTOS_ESPACIO + e.getMessage()); } } catch (HttpException e) { log.error(MENSAJE_VIOLACION_PROTOCOLO_HTTP + e.getMessage()); throw new TSClienteError( I18n.getResource(LIBRERIA_TSA_ERROR_6) + DOS_PUNTOS_ESPACIO + e.getMessage()); } catch (IOException e) { String mensajeError = I18n.getResource(LIBRERIA_TSA_ERROR_4) + DOS_PUNTOS_ESPACIO + servidorTSA; log.error(MENSAJE_ERROR_CONEXION_SERVIDOR_OCSP + e.getMessage()); throw new TSClienteError(mensajeError); } finally { // Termina la conexin metodo.releaseConnection(); } } }
From source file:it.eng.spagobi.engines.talend.client.SpagoBITalendEngineClient_0_5_0.java
public boolean deployJob(JobDeploymentDescriptor jobDeploymentDescriptor, File executableJobFiles) throws EngineUnavailableException, AuthenticationFailedException, ServiceInvocationFailedException { HttpClient client;/*from w w w.jav a 2s . co m*/ PostMethod method; File deploymentDescriptorFile; boolean result = false; client = new HttpClient(); method = new PostMethod(getServiceUrl(JOB_UPLOAD_SERVICE)); deploymentDescriptorFile = null; try { deploymentDescriptorFile = File.createTempFile("deploymentDescriptor", ".xml"); //$NON-NLS-1$ //$NON-NLS-2$ FileWriter writer = new FileWriter(deploymentDescriptorFile); writer.write(jobDeploymentDescriptor.toXml()); writer.flush(); writer.close(); Part[] parts = { new FilePart(executableJobFiles.getName(), executableJobFiles), new FilePart("deploymentDescriptor", deploymentDescriptorFile) }; //$NON-NLS-1$ method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); int status = client.executeMethod(method); if (status == HttpStatus.SC_OK) { if (method.getResponseBodyAsString().equalsIgnoreCase("OK")) //$NON-NLS-1$ result = true; } else { throw new ServiceInvocationFailedException( Messages.getString("SpagoBITalendEngineClient_0_5_0.serviceExcFailed") + JOB_UPLOAD_SERVICE, //$NON-NLS-1$ method.getStatusLine().toString(), method.getResponseBodyAsString()); } } catch (HttpException e) { throw new EngineUnavailableException( Messages.getString("SpagoBITalendEngineClient_0_5_0.protocolViolation") + e.getMessage()); //$NON-NLS-1$ } catch (IOException e) { throw new EngineUnavailableException( Messages.getString("SpagoBITalendEngineClient_0_5_0.transportError") + e.getMessage()); //$NON-NLS-1$ } finally { method.releaseConnection(); if (deploymentDescriptorFile != null) deploymentDescriptorFile.delete(); } return result; }
From source file:edu.unc.lib.dl.cdr.sword.server.test.DepositClientsByHand.java
@Test public void testUpload() throws Exception { String user = ""; String password = ""; String pid = "uuid:c9aba0a2-12e9-4767-822e-b285a37b07d7"; String payloadMimeType = "text/xml"; String payloadPath = "src/test/resources/dcDocument.xml"; String metadataPath = "src/test/resources/atompubMODS.xml"; String depositPath = "https://localhost:444/services/sword/collection/"; String testSlug = "ingesttestslug"; HttpClient client = HttpClientUtil.getAuthenticatedClient(depositPath + pid, user, password); client.getParams().setAuthenticationPreemptive(true); PostMethod post = new PostMethod(depositPath + pid); File payload = new File(payloadPath); File atom = new File(metadataPath); FilePart payloadPart = new FilePart("payload", payload); payloadPart.setContentType(payloadMimeType); payloadPart.setTransferEncoding("binary"); Part[] parts = { payloadPart, new FilePart("atom", atom, "application/atom+xml", "utf-8") }; MultipartRequestEntity mpEntity = new MultipartRequestEntity(parts, post.getParams()); String boundary = mpEntity.getContentType(); boundary = boundary.substring(boundary.indexOf("boundary=") + 9); Header header = new Header("Content-type", "multipart/related; type=application/atom+xml; boundary=" + boundary); post.addRequestHeader(header);//from w w w . j a v a 2 s. c o m Header slug = new Header("Slug", testSlug); post.addRequestHeader(slug); post.setRequestEntity(mpEntity); LOG.debug("" + client.executeMethod(post)); }
From source file:edu.stanford.muse.slant.CustomSearchHelper.java
private static void initializeCSE(String authtoken, String cseName) throws IOException { HttpClient client = new HttpClient(); //First perform the ClientLogin to get the authtoken //See http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html PostMethod create_post = new PostMethod("http://www.google.com/cse/api/default/cse/" + cseName); String new_annotation = "<CustomSearchEngine language=\"en\">" + "<Title>" + Util.escapeXML(cseName) + "</Title>" + "<Description>" + Util.escapeXML(cseName) + " - generated by Slant</Description>" + "<Context>" + "<BackgroundLabels>" + "<Label name=\"_cse_testengine\" mode=\"BOOST\" />" + "<Label name=\"_cse_exclude_testengine\" mode=\"ELIMINATE\" />" + // "<Label name=\"high\" mode=\"BOOST\" weight=\"1.0\"/>" + // "<Label name=\"medium\" mode=\"BOOST\" weight=\"0.8\"/>" + // "<Label name=\"low\" mode=\"BOOST\" weight=\"0.1\"/>" + "</BackgroundLabels>" + "</Context>" + "<LookAndFeel nonprofit=\"true\" />" + "<ImageSearchSettings enable=\"true\" />" + "</CustomSearchEngine>"; create_post.addRequestHeader("Content-type", "text/xml"); create_post.addRequestHeader("Authorization", "GoogleLogin auth=" + authtoken); StringRequestEntity rq_en = new StringRequestEntity(new_annotation, "text/xml", "UTF-8"); create_post.setRequestEntity(rq_en); // PostMethod create_post = new PostMethod("http://www.google.com/cse/api/default/cse/testengine"); /*//from w w w. j a v a 2 s .com String new_annotation ="<CustomSearchEngine language=\"en\">" + "<Title> CSE </Title>" + "<Description>Custom Search</Description>" + "<Context>" + "<BackgroundLabels>"+ "<Label name=\"_cse_testengine\" mode=\"FILTER\" />"+ "<Label name=\"_cse_exclude_testengine\" mode=\"ELIMINATE\" />"+ "<Label name=\"high\" mode=\"BOOST\" weight=\"1.0\"/>" + "<Label name=\"medium\" mode=\"BOOST\" weight=\"0.8\"/>" + "<Label name=\"low\" mode=\"BOOST\" weight=\"0.1\"/>" + "</BackgroundLabels>"+ "</Context>"+ "<LookAndFeel nonprofit=\"false\" />"+ "</CustomSearchEngine>"; create_post.addRequestHeader("Content-type", "text/xml"); create_post.addRequestHeader("Authorization", "GoogleLogin auth=" + authtoken); StringRequestEntity rq_en = new StringRequestEntity(new_annotation,"text/xml","UTF-8"); create_post.setRequestEntity(rq_en); */ int astatusCode = client.executeMethod(create_post); if (astatusCode == HttpStatus.SC_OK) { log.info("CSE " + cseName + " created"); //If successful, the CSE annotation is displayed in the response. log.info(create_post.getResponseBodyAsString()); } else log.warn("CSE " + cseName + " creation failed"); }
From source file:com.apatar.ui.JPublishToApatarDialog.java
Vector<PablishObject> getDataMapTags() throws HttpException, IOException, JDOMException { Vector<PablishObject> result = new Vector<PablishObject>(); PostMethod method = new PostMethod(apatarforgeUrl + "index.php"); Part[] parts = new Part[4]; parts[0] = new StringPart("option", "com_remository"); parts[1] = new StringPart("func", "select"); parts[2] = new StringPart("get", "tag"); parts[3] = new StringPart("no_html", "1"); method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(10000); int status = client.executeMethod(method); if (status == HttpStatus.SC_OK) { InputStream stream = method.getResponseBodyAsStream(); Document document = new Document(); SAXBuilder builder = new SAXBuilder(); document = builder.build(stream); for (Object obj : document.getRootElement().getChildren("tag")) { Element elem = (Element) obj; int id = Integer.parseInt(elem.getAttributeValue("id")); result.add(new PablishObject(id, elem.getChildText("name"))); }//from www .j av a 2s . c o m } return result; }
From source file:com.apatar.ui.JPublishToApatarDialog.java
Vector<PablishObject> getDataMapLocations() throws HttpException, IOException, JDOMException { Vector<PablishObject> result = new Vector<PablishObject>(); PostMethod method = new PostMethod(apatarforgeUrl + "index.php"); Part[] parts = new Part[4]; parts[0] = new StringPart("option", "com_remository"); parts[1] = new StringPart("func", "select"); parts[2] = new StringPart("get", "category"); parts[3] = new StringPart("no_html", "1"); method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(10000); int status = client.executeMethod(method); if (status == HttpStatus.SC_OK) { InputStream stream = method.getResponseBodyAsStream(); Document document = new Document(); SAXBuilder builder = new SAXBuilder(); document = builder.build(stream); for (Object obj : document.getRootElement().getChildren("category")) { Element elem = (Element) obj; int id = Integer.parseInt(elem.getAttributeValue("id")); result.add(new PablishObject(id, elem.getChildText("name"))); }//w w w . j a v a2 s .c om } return result; }
From source file:com.legstar.http.client.CicsHttp.java
/** * Create and populate an HTTP post method to send the execution request. * @param request the request to be serviced * @param hostURLPath the target host URL path * @return the new post method/*from w w w.j a v a2 s . co m*/ * @throws RequestException if post method cannot be created */ protected PostMethod createPostMethod(final LegStarRequest request, final String hostURLPath) throws RequestException { if (_log.isDebugEnabled()) { _log.debug("enter createPostMethod(request)"); } PostMethod postMethod = new PostMethod(); /* Point to URL under CICS Web Support */ postMethod.setPath(hostURLPath); /* Pass on trace data to host via HTTP headers */ postMethod.setRequestHeader(REQUEST_TRACE_MODE_HHDR, Boolean.toString(request.getAddress().isHostTraceMode())); postMethod.setRequestHeader(REQUEST_ID_HHDR, request.getID()); /* Create the binary content */ try { postMethod.setRequestEntity(new InputStreamRequestEntity(request.getRequestMessage().sendToHost(), APPLICATION_CONTENT_TYPE)); } catch (HostMessageFormatException e) { throw new RequestException(e); } return postMethod; }
From source file:is.idega.block.finance.business.sp.SPDataInsert.java
private void sendCreateClaimsRequest(BankFileManager bfm) { PostMethod filePost = new PostMethod(POST_METHOD); File file = new File(FILE_NAME); filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true); try {/*from w w w .j av a 2 s .c o m*/ StringPart userPart = new StringPart("notendanafn", bfm.getUsername()); StringPart pwdPart = new StringPart("password", bfm.getPassword()); StringPart clubssnPart = new StringPart("KtFelags", bfm.getClaimantSSN()); FilePart filePart = new FilePart("Skra", file); Part[] parts = { userPart, pwdPart, clubssnPart, filePart }; filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); int status = client.executeMethod(filePost); if (status == HttpStatus.SC_OK) { System.out.println("Upload complete, response=" + filePost.getResponseBodyAsString()); } else { System.out.println("Upload failed, response=" + HttpStatus.getStatusText(status)); } } catch (Exception ex) { ex.printStackTrace(); } finally { filePost.releaseConnection(); } }