List of usage examples for org.apache.commons.httpclient.methods InputStreamRequestEntity InputStreamRequestEntity
public InputStreamRequestEntity(InputStream paramInputStream)
From source file:es.mityc.firmaJava.ts.TSCliente.java
/** * Este mtodo genera el Sello de Tiempo//from w ww .j a v a 2s .c om * @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:com.moss.bdbadmin.client.service.BdbClient.java
public void put(IdProof assertion, String path, BdbResourceHandle handle) throws ServiceException { try {/*from ww w . j av a2s .c om*/ PutMethod method = new PutMethod(baseUrl + "/" + path); method.setRequestHeader(AuthenticationHeader.HEADER_NAME, AuthenticationHeader.encode(assertion)); method.setRequestEntity(new InputStreamRequestEntity(handle.read())); int result = httpClient.executeMethod(method); if (result != 200) { throw new ServiceException(result); } } catch (IOException ex) { throw new ServiceFailure(ex); } }
From source file:com.sun.syndication.propono.atom.client.ClientMediaEntry.java
/** * Update entry on server. /*from ww w . j a v a 2s .c om*/ */ public void update() throws ProponoException { if (partial) throw new ProponoException("ERROR: attempt to update partial entry"); EntityEnclosingMethod method = null; Content updateContent = (Content) getContents().get(0); try { if (getMediaLinkURI() != null && getBytes() != null) { // existing media entry and new file, so PUT file to edit-media URI method = new PutMethod(getMediaLinkURI()); if (inputStream != null) { method.setRequestEntity(new InputStreamRequestEntity(inputStream)); } else { method.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(getBytes()))); } method.setRequestHeader("Content-type", updateContent.getType()); } else if (getEditURI() != null) { // existing media entry and NO new file, so PUT entry to edit URI method = new PutMethod(getEditURI()); StringWriter sw = new StringWriter(); Atom10Generator.serializeEntry(this, sw); method.setRequestEntity(new StringRequestEntity(sw.toString())); method.setRequestHeader("Content-type", "application/atom+xml; charset=utf8"); } else { throw new ProponoException("ERROR: media entry has no edit URI or media-link URI"); } this.getCollection().addAuthentication(method); method.addRequestHeader("Title", getTitle()); getCollection().getHttpClient().executeMethod(method); if (inputStream != null) inputStream.close(); InputStream is = method.getResponseBodyAsStream(); if (method.getStatusCode() != 200 && method.getStatusCode() != 201) { throw new ProponoException( "ERROR HTTP status=" + method.getStatusCode() + " : " + Utilities.streamToString(is)); } } catch (Exception e) { throw new ProponoException("ERROR: saving media entry"); } if (method.getStatusCode() != 201) { throw new ProponoException("ERROR HTTP status=" + method.getStatusCode()); } }
From source file:fr.cls.atoll.motu.processor.wps.framework.WPSUtils.java
/** * Performs an HTTP-Get request and provides typed access to the response. * //from w w w .j a va2 s . c om * @param <T> * @param worker * @param url * @param postBody * @param headers * @return some object from the url * @throws HttpException * @throws IOException * @throws MotuException */ public static <T> T post(Worker<T> worker, String url, InputStream postBody, Map<String, String> headers) throws HttpException, IOException, MotuException { if (LOG.isDebugEnabled()) { LOG.debug("post(Worker<T>, String, InputStream, Map<String,String>) - start"); } ByteArrayOutputStream out = new ByteArrayOutputStream(); try { IOUtils.copy(postBody, out); } finally { IOUtils.closeQuietly(out); } InputStream postBodyCloned = new ByteArrayInputStream(out.toString().getBytes()); MultiThreadedHttpConnectionManager connectionManager = HttpUtil.createConnectionManager(); HttpClientCAS client = new HttpClientCAS(connectionManager); HttpClientParams clientParams = new HttpClientParams(); //clientParams.setParameter("http.protocol.allow-circular-redirects", true); //HttpClientParams.ALLOW_CIRCULAR_REDIRECTS client.setParams(clientParams); PostMethod post = new PostMethod(url); post.getParams().setCookiePolicy(CookiePolicy.RFC_2109); InputStreamRequestEntity inputStreamRequestEntity = new InputStreamRequestEntity(postBody); post.setRequestEntity(inputStreamRequestEntity); for (String key : headers.keySet()) { post.setRequestHeader(key, headers.get(key)); } String query = post.getQueryString(); // Check redirection // DONT USE post.setFollowRedirects(true); see http://hc.apache.org/httpclient-3.x/redirects.html int httpReturnCode = client.executeMethod(post); if (LOG.isDebugEnabled()) { String msg = String.format("Executing the query:\n==> http code: '%d':\n==> url: '%s'\n==> body:\n'%s'", httpReturnCode, url, query); LOG.debug("post(Worker<T>, String, InputStream, Map<String,String>) - end - " + msg); } if (httpReturnCode == 302) { post.releaseConnection(); String redirectLocation = null; Header locationHeader = post.getResponseHeader("location"); if (locationHeader != null) { redirectLocation = locationHeader.getValue(); if (!WPSUtils.isNullOrEmpty(redirectLocation)) { if (LOG.isDebugEnabled()) { String msg = String.format("Query is redirected to url: '%s'", redirectLocation); LOG.debug("post(Worker<T>, String, InputStream, Map<String,String>) - end - " + msg); } post = new PostMethod(url); post.setRequestEntity(new InputStreamRequestEntity(postBodyCloned)); // Recrire un nouveau InputStream for (String key : headers.keySet()) { post.setRequestHeader(key, headers.get(key)); } clientParams.setBooleanParameter(HttpClientCAS.ADD_CAS_TICKET_PARAM, false); httpReturnCode = client.executeMethod(post); clientParams.setBooleanParameter(HttpClientCAS.ADD_CAS_TICKET_PARAM, true); if (LOG.isDebugEnabled()) { String msg = String.format( "Executing the query:\n==> http code: '%d':\n==> url: '%s'\n==> body:\n'%s'", httpReturnCode, url, query); LOG.debug("post(Worker<T>, String, InputStream, Map<String,String>) - end - " + msg); } } } } T returnValue = worker.work(post.getResponseBodyAsStream()); if (httpReturnCode >= 400) { if (LOG.isDebugEnabled()) { LOG.debug("post(Worker<T>, String, InputStream, Map<String,String>) - end"); } String msg = String.format( "Error while executing the query:\n==> http code: '%d':\n==> url: '%s'\n==> body:\n'%s'", httpReturnCode, url, query); throw new MotuException(msg); } if (LOG.isDebugEnabled()) { LOG.debug("post(Worker<T>, String, InputStream, Map<String,String>) - end"); } return returnValue; }
From source file:eu.impact_project.resultsrepository.DavHandler.java
/** * Copies one file./*ww w.j a v a2 s.c om*/ * * @param sourceUrl * The remote URL of the file. * @param targetUrl * URL in the repository. */ private void copyFile(String sourceUrl, String targetUrl) throws HttpException, IOException { if (sourceUrl != null && !sourceUrl.equals("")) { GetMethod getMethod = new GetMethod(sourceUrl); PutMethod putMethod = new PutMethod(targetUrl); client.executeMethod(getMethod); downloadedFile = getMethod.getResponseBody(); InputStream stream = null; try { stream = new ByteArrayInputStream(downloadedFile); putMethod.setRequestEntity(new InputStreamRequestEntity(stream)); client.executeMethod(putMethod); } finally { stream.close(); } getMethod.releaseConnection(); putMethod.releaseConnection(); } else { throw new IOException("A tool did not return a URL. The target URL would have been: " + targetUrl); } }
From source file:com.rometools.propono.atom.client.ClientMediaEntry.java
/** * Update entry on server.// ww w .jav a2 s. c om */ @Override public void update() throws ProponoException { if (partial) { throw new ProponoException("ERROR: attempt to update partial entry"); } EntityEnclosingMethod method = null; final Content updateContent = getContents().get(0); try { if (getMediaLinkURI() != null && getBytes() != null) { // existing media entry and new file, so PUT file to edit-media URI method = new PutMethod(getMediaLinkURI()); if (inputStream != null) { method.setRequestEntity(new InputStreamRequestEntity(inputStream)); } else { method.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(getBytes()))); } method.setRequestHeader("Content-type", updateContent.getType()); } else if (getEditURI() != null) { // existing media entry and NO new file, so PUT entry to edit URI method = new PutMethod(getEditURI()); final StringWriter sw = new StringWriter(); Atom10Generator.serializeEntry(this, sw); method.setRequestEntity(new StringRequestEntity(sw.toString(), null, null)); method.setRequestHeader("Content-type", "application/atom+xml; charset=utf8"); } else { throw new ProponoException("ERROR: media entry has no edit URI or media-link URI"); } getCollection().addAuthentication(method); method.addRequestHeader("Title", getTitle()); getCollection().getHttpClient().executeMethod(method); if (inputStream != null) { inputStream.close(); } final InputStream is = method.getResponseBodyAsStream(); if (method.getStatusCode() != 200 && method.getStatusCode() != 201) { throw new ProponoException( "ERROR HTTP status=" + method.getStatusCode() + " : " + Utilities.streamToString(is)); } } catch (final Exception e) { throw new ProponoException("ERROR: saving media entry"); } if (method.getStatusCode() != 201) { throw new ProponoException("ERROR HTTP status=" + method.getStatusCode()); } }
From source file:com.predic8.membrane.interceptor.LoadBalancingInterceptorTest.java
private PostMethod getPostMethod() { PostMethod post = new PostMethod("http://localhost:7000/axis2/services/BLZService"); post.setRequestEntity(new InputStreamRequestEntity(this.getClass().getResourceAsStream("/getBank.xml"))); post.setRequestHeader(Header.CONTENT_TYPE, MimeType.TEXT_XML_UTF8); post.setRequestHeader(Header.SOAP_ACTION, ""); return post;//w ww . ja va 2 s . c om }
From source file:com.orange.mmp.net.http.HttpConnection.java
/** * Inner method used to execute request//from w w w . j av a 2 s .c om * * @param dataStream The data stream to send in request (null for GET only) * @throws MMPNetException */ @SuppressWarnings("unchecked") protected void doExecute(InputStream dataStream) throws MMPNetException { try { this.currentHttpClient = HttpConnectionManager.httpClientPool.take(); } catch (InterruptedException ie) { throw new MMPNetException("Corrupted HTTP client pool", ie); } if (this.httpConnectionProperties.containsKey(HttpConnectionParameters.PARAM_IN_CREDENTIALS_USER)) { this.currentHttpClient.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials( (String) this.httpConnectionProperties.get(HttpConnectionParameters.PARAM_IN_CREDENTIALS_USER), (String) this.httpConnectionProperties .get(HttpConnectionParameters.PARAM_IN_CREDENTIALS_PASSWORD))); this.currentHttpClient.getParams().setAuthenticationPreemptive(true); } // Config HostConfiguration config = new HostConfiguration(); if (this.timeout > 0) this.currentHttpClient.getParams().setParameter(HttpConnectionParameters.PARAM_IN_HTTP_SOCKET_TIMEOUT, this.timeout); if (HttpConnectionManager.proxyHost != null && (this.httpConnectionProperties.get(HttpConnectionParameters.PARAM_IN_HTTP_USE_PROXY) != null && this.httpConnectionProperties.get(HttpConnectionParameters.PARAM_IN_HTTP_USE_PROXY) .toString().equals("true")) || (this.httpConnectionProperties.get(HttpConnectionParameters.PARAM_IN_HTTP_USE_PROXY) == null && this.useProxy)) { config.setProxy(HttpConnectionManager.proxyHost, HttpConnectionManager.proxyPort); } else { config.setProxyHost(null); } this.currentHttpClient.setHostConfiguration(config); this.currentHttpClient.getHostConfiguration().setHost(new HttpHost(this.endPointUrl.getHost())); String methodStr = (String) this.httpConnectionProperties .get(HttpConnectionParameters.PARAM_IN_HTTP_METHOD); if (methodStr == null || methodStr.equals(HttpConnectionParameters.HTTP_METHOD_GET)) { this.method = new GetMethod(endPointUrl.toString().replace(" ", "+")); } else if (methodStr.equals(HttpConnectionParameters.HTTP_METHOD_POST)) { this.method = new PostMethod((this.endPointUrl.getQuery() == null) ? this.endPointUrl.getPath() : this.endPointUrl.getPath() + "?" + endPointUrl.getQuery()); if (dataStream != null) { InputStreamRequestEntity inputStreamRequestEntity = new InputStreamRequestEntity(dataStream); ((PostMethod) this.method).setRequestEntity(inputStreamRequestEntity); } } else if (methodStr.equals(HttpConnectionParameters.HTTP_METHOD_PUT)) { this.method = new PutMethod((this.endPointUrl.getQuery() == null) ? this.endPointUrl.getPath() : this.endPointUrl.getPath() + "?" + endPointUrl.getQuery()); if (dataStream != null) { InputStreamRequestEntity inputStreamRequestEntity = new InputStreamRequestEntity(dataStream); ((PutMethod) this.method).setRequestEntity(inputStreamRequestEntity); } } else if (methodStr.equals(HttpConnectionParameters.HTTP_METHOD_DEL)) { this.method = new DeleteMethod((this.endPointUrl.getQuery() == null) ? this.endPointUrl.getPath() : this.endPointUrl.getPath() + "?" + endPointUrl.getQuery()); } else throw new MMPNetException("HTTP method not supported"); //Add headers if (this.httpConnectionProperties != null) { for (Object headerName : this.httpConnectionProperties.keySet()) { if (!((String) headerName).startsWith("http.")) { this.method.addRequestHeader((String) headerName, this.httpConnectionProperties.get(headerName).toString()); } } } // Set Connection/Proxy-Connection close to avoid TIME_WAIT sockets this.method.addRequestHeader("Connection", "close"); this.method.addRequestHeader("Proxy-Connection", "close"); try { int httpCode = this.currentHttpClient.executeMethod(config, method); this.currentStatusCode = httpCode; for (org.apache.commons.httpclient.Header responseHeader : method.getResponseHeaders()) { this.httpConnectionProperties.put(responseHeader.getName(), responseHeader.getValue()); } if (this.currentStatusCode >= 400) { throw new MMPNetException("HTTP " + this.currentStatusCode + " on '" + endPointUrl + "'"); } else { this.inDataStream = this.method.getResponseBodyAsStream(); } } catch (IOException ioe) { throw new MMPNetException("I/O error on " + this.endPointUrl + " : " + ioe.getMessage()); } catch (Exception e) { e.printStackTrace(); } }
From source file:ar.com.zauber.commons.web.proxy.HttpClientRequestProxy.java
/** * @param request//from w w w . j a va2 s .c o m * @return */ private HttpMethod buildRequest(final HttpServletRequest request, final URLResult urlResult) { final String method = request.getMethod().toUpperCase(); final HttpMethod ret; final String uri = urlResult.getURL().toExternalForm(); if ("GET".equals(method)) { ret = new GetMethod(uri); proxyHeaders(request, ret); } else if ("POST".equals(method) || "PUT".equals(method)) { final EntityEnclosingMethod pm = "POST".equals(method) ? new PostMethod(uri) : new PutMethod(uri); proxyHeaders(request, pm); try { pm.setRequestEntity(new InputStreamRequestEntity(request.getInputStream())); } catch (IOException e) { throw new UnhandledException("No pudo abrirse el InputStream" + "del request.", e); } ret = pm; } else if ("DELETE".equals(method)) { /* rfc2616 The Content-Length field of a request or response is added or deleted according to the rules in section 4.4. A transparent proxy MUST preserve the entity-length (section 7.2.2) of the entity-body, although it MAY change the transfer-length (section 4.4). */ final DeleteMethod dm = new DeleteMethod(uri); proxyHeaders(request, dm); //No body => No Header dm.removeRequestHeader("Content-Length"); ret = dm; } else { throw new NotImplementedException("i accept patches :)"); } if (request.getQueryString() != null) { ret.setQueryString(request.getQueryString()); } return ret; }
From source file:com.sun.syndication.propono.atom.client.ClientMediaEntry.java
/** Package access, to be called by DefaultClientCollection */ void addToCollection(ClientCollection col) throws ProponoException { setCollection(col);/*from ww w. j a v a 2s . c o m*/ EntityEnclosingMethod method = new PostMethod(col.getHrefResolved()); getCollection().addAuthentication(method); StringWriter sw = new StringWriter(); boolean error = false; try { Content c = (Content) getContents().get(0); if (inputStream != null) { method.setRequestEntity(new InputStreamRequestEntity(inputStream)); } else { method.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(getBytes()))); } method.setRequestHeader("Content-type", c.getType()); method.setRequestHeader("Title", getTitle()); method.setRequestHeader("Slug", getSlug()); getCollection().getHttpClient().executeMethod(method); if (inputStream != null) inputStream.close(); InputStream is = method.getResponseBodyAsStream(); if (method.getStatusCode() == 200 || method.getStatusCode() == 201) { Entry romeEntry = Atom10Parser.parseEntry(new InputStreamReader(is), col.getHrefResolved()); BeanUtils.copyProperties(this, romeEntry); } else { throw new ProponoException("ERROR HTTP status-code=" + method.getStatusCode() + " status-line: " + method.getStatusLine()); } } catch (IOException ie) { throw new ProponoException("ERROR: saving media entry", ie); } catch (JDOMException je) { throw new ProponoException("ERROR: saving media entry", je); } catch (FeedException fe) { throw new ProponoException("ERROR: saving media entry", fe); } catch (IllegalAccessException ae) { throw new ProponoException("ERROR: saving media entry", ae); } catch (InvocationTargetException te) { throw new ProponoException("ERROR: saving media entry", te); } Header locationHeader = method.getResponseHeader("Location"); if (locationHeader == null) { logger.warn("WARNING added entry, but no location header returned"); } else if (getEditURI() == null) { List links = getOtherLinks(); Link link = new Link(); link.setHref(locationHeader.getValue()); link.setRel("edit"); links.add(link); setOtherLinks(links); } }