List of usage examples for org.apache.commons.httpclient.methods ByteArrayRequestEntity ByteArrayRequestEntity
public ByteArrayRequestEntity(byte[] paramArrayOfByte, String paramString)
From source file:com.ltasks.GZipPostMethod.java
@Override protected RequestEntity generateRequestEntity() { if (mIsGzip) { try {/* w ww . j a v a 2 s.c o m*/ String contentStr = EncodingUtil.formUrlEncode(getParameters(), getRequestCharSet()); ByteArrayOutputStream originalContent = new ByteArrayOutputStream(); originalContent.write(EncodingUtil.getAsciiBytes(contentStr)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); //ChunkedOutputStream chunkedOut = new ChunkedOutputStream(baos); GZIPOutputStream gzipOut = new GZIPOutputStream(baos); originalContent.writeTo(gzipOut); gzipOut.finish(); byte[] content = baos.toByteArray(); ByteArrayRequestEntity entity = new ByteArrayRequestEntity(content, FORM_URL_ENCODED_CONTENT_TYPE); return entity; } catch (Exception e) { e.printStackTrace(); } return null; } else { return super.generateRequestEntity(); } }
From source file:be.fedict.trust.service.util.ClockDriftUtil.java
public static Date executeTSP(ClockDriftConfigEntity clockDriftConfig, NetworkConfig networkConfig) throws IOException, TSPException { LOG.debug("clock drift detection: " + clockDriftConfig.toString()); TimeStampRequestGenerator requestGen = new TimeStampRequestGenerator(); TimeStampRequest request = requestGen.generate(TSPAlgorithms.SHA1, new byte[20], BigInteger.valueOf(100)); byte[] requestData = request.getEncoded(); HttpClient httpClient = new HttpClient(); if (null != networkConfig) { httpClient.getHostConfiguration().setProxy(networkConfig.getProxyHost(), networkConfig.getProxyPort()); }/*from w w w. j a va 2 s. c o m*/ PostMethod postMethod = new PostMethod(clockDriftConfig.getServer()); postMethod.setRequestEntity(new ByteArrayRequestEntity(requestData, "application/timestamp-query")); int statusCode = httpClient.executeMethod(postMethod); if (statusCode != HttpStatus.SC_OK) { throw new TSPException("Error contacting TSP server " + clockDriftConfig.getServer()); } TimeStampResponse tspResponse = new TimeStampResponse(postMethod.getResponseBodyAsStream()); postMethod.releaseConnection(); return tspResponse.getTimeStampToken().getTimeStampInfo().getGenTime(); }
From source file:com.mindquarry.desktop.util.HttpUtilities.java
public static String putAsXML(String login, String pwd, String address, byte[] content) throws NotAuthorizedException { try {/*from w w w . j av a 2 s . c o m*/ HttpClient client = createHttpClient(login, pwd, address); PutMethod put = new PutMethod(address); put.setDoAuthentication(true); put.addRequestHeader("accept", "text/xml"); //$NON-NLS-1$ //$NON-NLS-2$ put.setRequestEntity(new ByteArrayRequestEntity(content, "text/xml; charset=utf-8")); log.info("Executing HTTP PUT on " + address); //$NON-NLS-1$ client.executeMethod(put); log.info("Finished HTTP PUT with status code: "//$NON-NLS-1$ + put.getStatusCode()); String id = null; if (put.getStatusCode() == 401) { throw new NotAuthorizedException(AUTH_REFUSED, address, login, pwd); } else if (put.getStatusCode() == 302) { Header locationHeader = put.getResponseHeader("location"); if (locationHeader != null) { // we received a redirect to the URL of the putted document, // so // everything seems right and we just use the new ID: id = locationHeader.getValue(); } else { throw new RuntimeException(CONNECTION_ERROR + put.getStatusCode()); } } else { throw new RuntimeException(CONNECTION_ERROR + put.getStatusCode()); } put.releaseConnection(); return id; } catch (NotAuthorizedException e) { throw e; } catch (Exception e) { throw new RuntimeException(e.toString(), e); } }
From source file:com.curl.orb.client.ClientUtil.java
Object requestToORB(InstanceManagementRequest request, String uri, boolean hasManyResult) throws ORBClientException, ORBServerException { AbstractSerializer serializer = SerializerFactory.getInstance().getSerializer(); OutputStream outputStream = new ByteArrayOutputStream(); Object returnedObject = null; InputStream inputStream = null; PostMethod method = null;/*w w w . java2s . co m*/ try { serializer.serialize(request, null, outputStream); httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); method = new PostMethod(uri); method.setRequestHeader("Content-Length", ((ByteArrayOutputStream) outputStream).size() + ""); method.setRequestEntity(new ByteArrayRequestEntity(((ByteArrayOutputStream) outputStream).toByteArray(), "application/octet-stream; charset=UTF-8")); httpClient.executeMethod(method); method.getResponseBody(); inputStream = (ByteArrayInputStream) method.getResponseBodyAsStream(); SerializableStreamReader deserializer = new CurlSerializableStreamReader(inputStream); returnedObject = ((InstanceManagementResponse) deserializer.read()).getBody(); if (hasManyResult) { List<Object> resultList = new ArrayList<Object>(); resultList.add(returnedObject); Object innerresult = null; while ((innerresult = deserializer.read()) != null) resultList.add(innerresult); return resultList; } if (returnedObject instanceof ExceptionContent) { throw new ORBServerException((ExceptionContent) returnedObject); } } catch (SerializerException e) { throw new ORBClientException(e); } catch (HttpException e) { throw new ORBClientException(e); } catch (IOException e) { throw new ORBClientException(e); } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { throw new ORBClientException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { throw new ORBClientException(e); } } method.releaseConnection(); } } } return returnedObject; }
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 ww.j av a2s .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:edu.usc.corral.api.Client.java
public <T> T doPost(String path, Class<? extends T> responseType, Object request) throws GlideinException { ensureOpen();// w w w . j a v a 2s . co m Serializer serializer = new Persister(); RequestEntity entity = null; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); serializer.write(request, baos); entity = new ByteArrayRequestEntity(baos.toByteArray(), "text/xml"); } catch (Exception e) { throw new GlideinException("Unable to generate request xml", e); } PostMethod post = new PostMethod(path); try { post.setRequestEntity(entity); int status = httpclient.executeMethod(post); InputStream is = post.getResponseBodyAsStream(); if (status < 200 || status > 299) { handleError(is); } return serializer.read(responseType, is); } catch (HttpException he) { throw new GlideinException("Error parsing http", he); } catch (IOException ioe) { throw new GlideinException("Error communicating with server", ioe); } catch (GlideinException ge) { throw ge; } catch (Exception e) { throw new GlideinException("Unable to parse response xml", e); } finally { post.releaseConnection(); } }
From source file:eu.learnpad.rest.utils.internal.DefaultRestUtils.java
@Override public boolean putAttachment(String spaceName, String pageName, String attachmentName, byte[] attachment) { HttpClient httpClient = getClient(); String uri = REST_URI + "/wikis/xwiki/spaces/" + spaceName + "/pages/" + pageName + "/attachments/" + attachmentName;//w ww . j a v a 2 s. c om PutMethod putMethod = new PutMethod(uri); putMethod.addRequestHeader("Accept", "application/xml"); putMethod.addRequestHeader("Accept-Ranges", "bytes"); RequestEntity fileRequestEntity = new ByteArrayRequestEntity(attachment, "application/xml"); putMethod.setRequestEntity(fileRequestEntity); try { httpClient.executeMethod(putMethod); return true; } catch (HttpException e) { logger.error("Unable to process PUT request for the attachment '" + spaceName + "." + pageName + "/" + attachmentName + "'.", e); return false; } catch (IOException e) { logger.error( "Unable to PUT the attachment '" + spaceName + "." + pageName + "/" + attachmentName + "'.", e); return false; } }
From source file:com.zimbra.cs.dav.client.WebDavClient.java
public HttpInputStream sendPut(String href, byte[] buf, String contentType, String etag, Collection<Pair<String, String>> headers) throws IOException { boolean done = false; PutMethod put = null;//from ww w. ja v a 2 s . c o m while (!done) { put = new PutMethod(mBaseUrl + href); put.setRequestEntity(new ByteArrayRequestEntity(buf, contentType)); if (mDebugEnabled && contentType.startsWith("text")) ZimbraLog.dav.debug("PUT payload: \n" + new String(buf, "UTF-8")); if (etag != null) put.setRequestHeader(DavProtocol.HEADER_IF_MATCH, etag); if (headers != null) for (Pair<String, String> h : headers) put.addRequestHeader(h.getFirst(), h.getSecond()); executeMethod(put, Depth.zero); int ret = put.getStatusCode(); if (ret == HttpStatus.SC_MOVED_PERMANENTLY || ret == HttpStatus.SC_MOVED_TEMPORARILY) { Header newLocation = put.getResponseHeader("Location"); if (newLocation != null) { href = newLocation.getValue(); ZimbraLog.dav.debug("redirect to new url = " + href); put.releaseConnection(); continue; } } done = true; } return new HttpInputStream(put); }
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 a 2 s. com * @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.duowan.common.rpc.client.CommonsHttpInvokerRequestExecutor.java
/** * Set the given serialized remote invocation as request body. * <p>The default implementation simply sets the serialized invocation * as the PostMethod's request body. This can be overridden, for example, * to write a specific encoding and potentially set appropriate HTTP * request headers.// www.j a v a2 s. c om * @param config the HTTP invoker configuration that specifies the target service * @param postMethod the PostMethod to set the request body on * @param baos the ByteArrayOutputStream that contains the serialized * RemoteInvocation object * @throws IOException if thrown by I/O methods * @see org.apache.commons.httpclient.methods.PostMethod#setRequestBody(java.io.InputStream) * @see org.apache.commons.httpclient.methods.PostMethod#setRequestEntity * @see org.apache.commons.httpclient.methods.InputStreamRequestEntity */ protected void setRequestBody(PostMethod postMethod, byte[] parameters) throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); outputStream.write(parameters); outputStream.close(); postMethod.setRequestEntity(new ByteArrayRequestEntity(outputStream.toByteArray(), getContentType())); }