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); } 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(); } }
public void testEnclosedEntityAutoLength() throws Exception { String inputstr = "This is a test message"; byte[] input = inputstr.getBytes("US-ASCII"); InputStream instream = new ByteArrayInputStream(input); RequestEntity requestentity = new InputStreamRequestEntity( instream, InputStreamRequestEntity.CONTENT_LENGTH_AUTO); PostMethod method = new PostMethod("/"); method.setRequestEntity(requestentity); this.server.setHttpService(new EchoService()); try { this.client.executeMethod(method); assertEquals(200, method.getStatusCode()); String body = method.getResponseBodyAsString(); assertEquals(inputstr, body); assertNull(method.getRequestHeader("Transfer-Encoding")); assertNotNull(method.getRequestHeader("Content-Length")); assertEquals(input.length, Integer.parseInt( method.getRequestHeader("Content-Length").getValue())); } finally { method.releaseConnection(); } }
public void testEnclosedEntityExplicitLength() throws Exception { String inputstr = "This is a test message"; byte[] input = inputstr.getBytes("US-ASCII"); InputStream instream = new ByteArrayInputStream(input); RequestEntity requestentity = new InputStreamRequestEntity( instream, 14); PostMethod method = new PostMethod("/"); method.setRequestEntity(requestentity); this.server.setHttpService(new EchoService()); try { this.client.executeMethod(method); assertEquals(200, method.getStatusCode()); String body = method.getResponseBodyAsString(); assertEquals("This is a test", body); assertNull(method.getRequestHeader("Transfer-Encoding")); assertNotNull(method.getRequestHeader("Content-Length")); assertEquals(14, Integer.parseInt( method.getRequestHeader("Content-Length").getValue())); } finally { method.releaseConnection(); } }
public void testEnclosedEntityChunked() throws Exception { String inputstr = "This is a test message"; byte[] input = inputstr.getBytes("US-ASCII"); InputStream instream = new ByteArrayInputStream(input); RequestEntity requestentity = new InputStreamRequestEntity( instream, InputStreamRequestEntity.CONTENT_LENGTH_AUTO); PostMethod method = new PostMethod("/"); method.setRequestEntity(requestentity); method.setContentChunked(true); this.server.setHttpService(new EchoService()); try { this.client.executeMethod(method); assertEquals(200, method.getStatusCode()); String body = method.getResponseBodyAsString(); assertEquals(inputstr, body); assertNotNull(method.getRequestHeader("Transfer-Encoding")); assertNull(method.getRequestHeader("Content-Length")); } finally { method.releaseConnection(); } }
public void testEnclosedEntityChunkedHTTP1_0() throws Exception { String inputstr = "This is a test message"; byte[] input = inputstr.getBytes("US-ASCII"); InputStream instream = new ByteArrayInputStream(input); RequestEntity requestentity = new InputStreamRequestEntity( instream, InputStreamRequestEntity.CONTENT_LENGTH_AUTO); PostMethod method = new PostMethod("/"); method.setRequestEntity(requestentity); method.setContentChunked(true); method.getParams().setVersion(HttpVersion.HTTP_1_0); this.server.setHttpService(new EchoService()); try { this.client.executeMethod(method); fail("ProtocolException should have been thrown"); } catch (ProtocolException ex) { // expected } finally { method.releaseConnection(); } }
public void testEnclosedEntityNegativeLength() throws Exception { String inputstr = "This is a test message"; byte[] input = inputstr.getBytes("US-ASCII"); InputStream instream = new ByteArrayInputStream(input); RequestEntity requestentity = new InputStreamRequestEntity( instream, -14); PostMethod method = new PostMethod("/"); method.setRequestEntity(requestentity); method.setContentChunked(false); this.server.setHttpService(new EchoService()); try { this.client.executeMethod(method); assertEquals(200, method.getStatusCode()); String body = method.getResponseBodyAsString(); assertEquals(inputstr, body); assertNotNull(method.getRequestHeader("Transfer-Encoding")); assertNull(method.getRequestHeader("Content-Length")); } finally { method.releaseConnection(); } }
public void testEnclosedEntityNegativeLengthHTTP1_0() throws Exception { String inputstr = "This is a test message"; byte[] input = inputstr.getBytes("US-ASCII"); InputStream instream = new ByteArrayInputStream(input); RequestEntity requestentity = new InputStreamRequestEntity( instream, -14); PostMethod method = new PostMethod("/"); method.setRequestEntity(requestentity); method.setContentChunked(false); method.getParams().setVersion(HttpVersion.HTTP_1_0); this.server.setHttpService(new EchoService()); try { this.client.executeMethod(method); fail("ProtocolException should have been thrown"); } catch (ProtocolException ex) { // expected } finally { method.releaseConnection(); } }
private void createRequest(final RequestParameters requestParameters, final PostMethod httpPost) throws IOException, ParserConfigurationException, SAXException { InputStream inputStream = requestParameters.getInputStream(); if (requestParameters.getContentType().contains("fastinfoset")) { inputStream = fastInfosetCompressor.compress(inputStream); } if (requestParameters.getContentEncoding().contains("gzip")) { inputStream = gzipCompressor.compress(inputStream); httpPost.setRequestHeader("Content-Encoding", requestParameters.getContentEncoding()); } final InputStreamRequestEntity entity = new InputStreamRequestEntity(inputStream, requestParameters.getContentType()); httpPost.setRequestEntity(entity); httpPost.setRequestHeader("Accept", requestParameters.getAcceptHeader()); httpPost.addRequestHeader("Accept-Encoding", requestParameters.getAcceptEncoding()); if (requestParameters.getSpecialHeader() != null) { httpPost.addRequestHeader("Special-Header", requestParameters.getSpecialHeader()); } for (Entry<String, String> header : requestParameters.getCustomHeaders()) { httpPost.addRequestHeader(header.getKey(), header.getValue()); } }
private void createRequest(final MultiStubRequestParameters requestParameters, final PostMethod httpPost) throws IOException, ParserConfigurationException, SAXException { InputStream inputStream = requestParameters.getInputStream(); if (requestParameters.getContentType().contains("fastinfoset")) { inputStream = fastInfosetCompressor.compress(inputStream); } if (requestParameters.getContentEncoding().contains("gzip")) { inputStream = gzipCompressor.compress(inputStream); httpPost.setRequestHeader("Content-Encoding", requestParameters.getContentEncoding()); } final InputStreamRequestEntity entity = new InputStreamRequestEntity(inputStream, requestParameters.getContentType()); httpPost.setRequestEntity(entity); httpPost.setRequestHeader("Accept", requestParameters.getAcceptHeader()); httpPost.addRequestHeader("Accept-Encoding", requestParameters.getAcceptEncoding()); if (requestParameters.getSpecialHeader() != null) { httpPost.addRequestHeader("Special-Header", requestParameters.getSpecialHeader()); } httpPost.addParameter("nextstatus", requestParameters.getStatus()); httpPost.addParameter("direction", requestParameters.getDirection()); httpPost.addParameter("groupname", requestParameters.getGroupName()); }
public boolean davPut(File upload, String toPath) { try { PutMethod put = new PutMethod(getResourceUrl(toPath)); RequestEntity requestEntity = new InputStreamRequestEntity(new BufferedInputStream( new FileInputStream(upload), HttpServices.BUFFER_SIZE), upload.length()); put.setRequestEntity(requestEntity); /** is to allow a client that is sending a request message with a request body * to determine if the origin server is willing to accept the request * (based on the request headers) before the client sends the request body. * this require server supporting HTTP/1.1 protocol. */ put.getParams().setBooleanParameter( HttpMethodParams.USE_EXPECT_CONTINUE, true); if (!executeMethod(put)) { // handle error System.out.println("Unable to upload file:" + toPath + " -- " + put.getStatusText()); return false; } return true; } catch (Exception e) { LOG.error(e, "Error while uploading file:" + upload.getPath()); } return false; }
/** * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same multipart POST data * as was sent in the given {@link HttpServletRequest} * * @param postMethodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are configuring to send a * multipart POST request * @param httpServletRequest The {@link HttpServletRequest} that contains the multipart * POST data to be sent via the {@link org.apache.commons.httpclient.methods.PostMethod} */ @SuppressWarnings("unchecked") public static void handleMultipartPost( EntityEnclosingMethod postMethodProxyRequest, HttpServletRequest httpServletRequest, DiskFileItemFactory diskFileItemFactory) throws ServletException { // TODO: this function doesn't set any history data try { // just pass back the binary data InputStreamRequestEntity ire = new InputStreamRequestEntity(httpServletRequest.getInputStream()); postMethodProxyRequest.setRequestEntity(ire); postMethodProxyRequest.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME, httpServletRequest.getHeader(STRING_CONTENT_TYPE_HEADER_NAME)); } catch (Exception e) { throw new ServletException(e); } }
/** * Saves a stream into a file in the repository. * * @param text * Stream to be stored. * @param url * URL to the file that will be created. */ public void saveStream(InputStream stream, String url) throws IOException { PutMethod putMethod = new PutMethod(url); putMethod.setRequestEntity(new InputStreamRequestEntity(stream)); try { client.executeMethod(putMethod); putMethod.releaseConnection(); } catch (IOException e) { throw new IOException(e); } finally { stream.close(); } }
@Test public void testRetrieveTextFile() throws HttpException, IOException { DavHandler dav = new DavHandler(folders); InputStream stream = new ByteArrayInputStream("some text".getBytes()); PutMethod putMethod = new PutMethod( "http://localhost:9002/parent/child/textToRetrieve.txt"); putMethod.setRequestEntity(new InputStreamRequestEntity(stream)); HttpClient client = new HttpClient(); client.executeMethod(putMethod); stream.close(); putMethod.releaseConnection(); String retrieved = dav.retrieveTextFile("http://localhost:9002/parent/child/textToRetrieve.txt"); assertEquals("some text", retrieved); }
/** * Kicks the GDC platform to inform it that the FTP transfer is finished. * * @param projectId the project's ID * @param remoteDir the remote (FTP) directory that contains the data * @return the link that is used for polling the loading progress * @throws GdcRestApiException */ public String startLoading(String projectId, String remoteDir) throws GdcRestApiException { l.debug("Initiating data load project id=" + projectId + " remoteDir=" + remoteDir); PostMethod pullPost = createPostMethod(getProjectMdUrl(projectId) + PULL_URI); JSONObject pullStructure = getPullStructure(remoteDir); InputStreamRequestEntity request = new InputStreamRequestEntity(new ByteArrayInputStream(pullStructure.toString().getBytes())); pullPost.setRequestEntity(request); String taskLink = null; try { String response = executeMethodOk(pullPost); JSONObject responseObject = JSONObject.fromObject(response); taskLink = responseObject.getJSONObject("pullTask").getString("uri"); } catch (HttpMethodException ex) { throw new GdcRestApiException("Loading fails: " + ex.getMessage()); } finally { pullPost.releaseConnection(); } l.debug("Data load project id=" + projectId + " remoteDir=" + remoteDir + " initiated. Status is on uri=" + taskLink); return taskLink; }
/** * Executes the MAQL and creates/modifies the project's LDM * * @param projectId the project's ID * @param maql String with the MAQL statements * @return result String * @throws GdcRestApiException */ public String[] executeMAQL(String projectId, String maql) throws GdcRestApiException { l.debug("Executing MAQL projectId=" + projectId + " MAQL:\n" + maql); PostMethod maqlPost = createPostMethod(getProjectMdUrl(projectId) + MAQL_EXEC_URI); JSONObject maqlStructure = getMAQLExecStructure(maql); InputStreamRequestEntity request = new InputStreamRequestEntity(new ByteArrayInputStream( maqlStructure.toString().getBytes())); maqlPost.setRequestEntity(request); String result = null; try { String response = executeMethodOk(maqlPost); JSONObject responseObject = JSONObject.fromObject(response); JSONArray uris = responseObject.getJSONArray("uris"); return (String[]) uris.toArray(new String[]{""}); } catch (HttpMethodException ex) { l.debug("MAQL execution: ", ex); throw new GdcRestApiException("MAQL execution: " + ex.getMessage(), ex); } finally { maqlPost.releaseConnection(); } }
/** * Create a new user * * @param domain the domain where the user is going to be created * @param user new user data * @return the new user's URI * @throws GdcRestApiException */ public String createUser(String domain, GdcUser user) throws GdcRestApiException { if (user != null && user.validate()) { l.debug("Creating new user " + user.getLogin() + " in domain " + domain); PostMethod req = createPostMethod(getServerUrl() + DOMAIN_URI + "/" + domain + DOMAIN_USERS_SUFFIX); JSONObject param = getCreateUserStructure(user); InputStreamRequestEntity request = new InputStreamRequestEntity(new ByteArrayInputStream( param.toString().getBytes())); req.setRequestEntity(request); String result = null; try { String response = executeMethodOk(req); JSONObject responseObject = JSONObject.fromObject(response); result = responseObject.getString("uri"); return result; } catch (HttpMethodException ex) { l.debug("Error creating user ", ex); throw new GdcRestApiException("Error creating user ", ex); } finally { req.releaseConnection(); } } else { throw new InvalidParameterException("The new user must contain valid login, firstName, lastName, and password fields."); } }
/** * Imports the project * * @param projectId the project's ID * @param token export token * @return result the taskUri * @throws GdcRestApiException */ public String importProject(String projectId, String token) throws GdcRestApiException { l.debug("Importing project projectId=" + projectId + " token:" + token); PostMethod req = createPostMethod(getProjectMdUrl(projectId) + PROJECT_IMPORT_URI); JSONObject param = getImportProjectStructure(token); InputStreamRequestEntity request = new InputStreamRequestEntity(new ByteArrayInputStream( param.toString().getBytes())); req.setRequestEntity(request); String result = null; try { String response = executeMethodOk(req); JSONObject responseObject = JSONObject.fromObject(response); result = responseObject.getString("uri"); return result; } catch (HttpMethodException ex) { l.debug("Error importing project", ex); throw new GdcRestApiException("Error importing project", ex); } finally { req.releaseConnection(); } }
/** * Imports a MD object to the project * * @param projectId the project's ID * @param token export token * @param overwrite overwrite existing objects * @param updateLDM update LDM names, descriptions and tags * @return result the taskUri * @throws GdcRestApiException */ public String importMD(String projectId, String token, boolean overwrite, boolean updateLDM) throws GdcRestApiException { l.debug("Importing metadata objects for projectId=" + projectId + " token:" + token); PostMethod req = createPostMethod(getProjectMdUrl(projectId) + PROJECT_PARTIAL_IMPORT_URI); JSONObject param = getMDImportStructure(token, overwrite, updateLDM); InputStreamRequestEntity request = new InputStreamRequestEntity(new ByteArrayInputStream( param.toString().getBytes())); req.setRequestEntity(request); String result = null; try { String response = executeMethodOk(req); JSONObject responseObject = JSONObject.fromObject(response); result = responseObject.getString("uri"); return result; } catch (HttpMethodException ex) { l.debug("Error importing metadata objects for projectId=" + projectId + " token:" + token, ex); throw new GdcRestApiException("Error importing metadata objects for projectId=" + projectId + " token:" + token, ex); } finally { req.releaseConnection(); } }
/** * Exports selected MD object with dependencies from the project * * @param projectId the project's ID * @param ids - list of the exported MD objects IDs * @return result the taskUri and the export token * @throws GdcRestApiException */ public ProjectExportResult exportMD(String projectId, List<Integer> ids) throws GdcRestApiException { l.debug("Exporting metadata objects with IDs " + ids + " from project " + projectId); PostMethod req = createPostMethod(getProjectMdUrl(projectId) + PROJECT_PARTIAL_EXPORT_URI); JSONObject param = getMDExportStructure(projectId, ids); InputStreamRequestEntity request = new InputStreamRequestEntity(new ByteArrayInputStream( param.toString().getBytes())); req.setRequestEntity(request); ProjectExportResult result = null; try { String response = executeMethodOk(req); result = new ProjectExportResult(); JSONObject responseObject = JSONObject.fromObject(response); JSONObject exportArtifact = responseObject.getJSONObject("partialMDArtifact"); JSONObject status = exportArtifact.getJSONObject("status"); result.setTaskUri(status.getString("uri")); result.setExportToken(exportArtifact.getString("token")); return result; } catch (HttpMethodException ex) { l.debug("Error exporting metadata objects with IDs " + ids + " from project " + projectId, ex); throw new GdcRestApiException("Error exporting metadata objects with IDs " + ids + " from project " + projectId, ex); } finally { req.releaseConnection(); } }
/** * Executes the MAQL and creates/modifies the project's LDM * * @param projectId the project's ID * @param maql String with the MAQL statements * @return result {@link GraphExecutionResult} * @throws GdcRestApiException */ public GraphExecutionResult executeGraph(String processUri, String graph, Map<String,String> params, Map<String,String> hiddenParams) throws GdcRestApiException { l.debug("Executing Graph processUri=" + processUri + " graph = " + graph); if (hiddenParams == null) { hiddenParams = new HashMap<String, String>(); } PostMethod execPost = createPostMethod(processUri + "/executions"); JSONObject execStructure = getGraphExecStructure(graph, params, hiddenParams); InputStreamRequestEntity request = new InputStreamRequestEntity(new ByteArrayInputStream( execStructure.toString().getBytes())); execPost.setRequestEntity(request); try { String response = executeMethodOk(execPost); JSONObject responseObject = JSONObject.fromObject(response); String detailUri = responseObject.getJSONObject("executionTask").getJSONObject("links").getString("detail"); GraphExecutionResult execResult = getGraphExecutionResult(detailUri); if (!GraphExecutionResult.OK.equals(execResult.getStatus())) { throw new GdcRestApiException("ETL error, see log file at " + execResult.logUrl); } return execResult; } finally { execPost.releaseConnection(); } }
/** * Executes the MAQL and creates/modifies the project's LDM * * @param projectId the project's ID * @param maql String with the MAQL statements * @return result String * @throws GdcRestApiException */ public String executeDML(String projectId, String maql) throws GdcRestApiException { l.debug("Executing MAQL DML projectId=" + projectId + " MAQL DML:\n" + maql); PostMethod maqlPost = createPostMethod(getProjectMdUrl(projectId) + DML_EXEC_URI); JSONObject maqlStructure = getMAQLExecStructure(maql); InputStreamRequestEntity request = new InputStreamRequestEntity(new ByteArrayInputStream( maqlStructure.toString().getBytes())); maqlPost.setRequestEntity(request); String result = null; try { String response = executeMethodOk(maqlPost); JSONObject responseObject = JSONObject.fromObject(response); String uris = responseObject.getString("uri"); return uris; } catch (HttpMethodException ex) { l.debug("MAQL DML execution: ", ex); throw new GdcRestApiException("MAQL DML execution: ", ex); } finally { maqlPost.releaseConnection(); } }
/** * Invites a new user to a project * * @param projectId project ID * @param eMail invited user e-mail * @param message invitation message */ public void inviteUser(String projectId, String eMail, String message, String role) { l.debug("Executing inviteUser projectId=" + projectId + " e-mail=" + eMail + " message=" + message); PostMethod invitePost = createPostMethod(getServerUrl() + getProjectDeleteUri(projectId) + INVITATION_URI); JSONObject inviteStructure = getInviteStructure(projectId, eMail, message, role); InputStreamRequestEntity request = new InputStreamRequestEntity(new ByteArrayInputStream( inviteStructure.toString().getBytes())); invitePost.setRequestEntity(request); try { executeMethodOk(invitePost); } catch (HttpMethodException ex) { l.debug("Failed executing inviteUser projectId=" + projectId + " e-mail=" + eMail + " message=" + message); throw new GdcRestApiException("Failed executing inviteUser projectId=" + projectId + " e-mail=" + eMail + " message=" + message, ex); } finally { invitePost.releaseConnection(); } }
/** * Creates a new object in the metadata server * * @param projectId project id (hash) * @param content the new object content * @return the new object */ public JSONObject createMetadataObject(String projectId, JSON content) { l.debug("Executing createMetadataObject on project id=" + projectId + "content='" + content.toString() + "'"); PostMethod req = createPostMethod(getProjectMdUrl(projectId) + OBJ_URI + "?createAndGet=true"); try { String str = content.toString(); InputStreamRequestEntity request = new InputStreamRequestEntity(new ByteArrayInputStream(str.getBytes("utf-8"))); req.setRequestEntity(request); String resp = executeMethodOk(req); JSONObject parsedResp = JSONObject.fromObject(resp); return parsedResp; } catch (HttpMethodException ex) { l.debug("Failed executing createMetadataObject on project id=" + projectId + "content='" + content.toString() + "'"); throw new GdcRestApiException("Failed executing createMetadataObject on project id=" + projectId + "content='" + content.toString() + "'", ex); } catch (UnsupportedEncodingException e) { l.debug("String#getBytes(\"utf-8\") threw UnsupportedEncodingException", e); throw new IllegalStateException(e); } finally { req.releaseConnection(); } }
/** * Modifies an object in the metadata server * * @param uri object uri * @param content the new object content * @return the new object */ public JSONObject modifyMetadataObject(String uri, JSON content) { l.debug("Executing modifyMetadataObject on uri=" + uri + " content='" + content.toString() + "'"); PostMethod req = createPostMethod(getServerUrl() + uri); try { InputStreamRequestEntity request = new InputStreamRequestEntity(new ByteArrayInputStream( content.toString().getBytes("utf-8"))); req.setRequestEntity(request); String resp = executeMethodOk(req); JSONObject parsedResp = JSONObject.fromObject(resp); return parsedResp; } catch (HttpMethodException ex) { l.debug("Failed executing modifyMetadataObject on uri=" + uri + " content='" + content.toString() + "'"); throw new GdcRestApiException("Failed executing modifyMetadataObject on uri=" + uri + " content='" + content.toString() + "'", ex); } catch (UnsupportedEncodingException e) { l.debug("String#getBytes(\"utf-8\") threw UnsupportedEncodingException", e); throw new IllegalStateException(e); } finally { req.releaseConnection(); } }
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); } 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))); httppost.setContentChunked(true); 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(); } }
public void testEnclosedEntityRepeatable() throws Exception { String inputstr = "This is a test message"; byte[] input = inputstr.getBytes("US-ASCII"); InputStream instream = new ByteArrayInputStream(input); RequestEntity requestentity = new InputStreamRequestEntity( instream, InputStreamRequestEntity.CONTENT_LENGTH_AUTO); PostMethod method = new PostMethod("/"); method.setRequestEntity(requestentity); UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds)); handlerchain.appendHandler(new HttpServiceHandler(new EchoService())); this.server.setRequestHandler(handlerchain); this.client.getState().setCredentials(AuthScope.ANY, creds); try { this.client.executeMethod(method); assertEquals(200, method.getStatusCode()); String body = method.getResponseBodyAsString(); assertEquals(inputstr, body); assertNull(method.getRequestHeader("Transfer-Encoding")); assertNotNull(method.getRequestHeader("Content-Length")); assertEquals(input.length, Integer.parseInt( method.getRequestHeader("Content-Length").getValue())); } finally { method.releaseConnection(); } }
public void testEnclosedEntityNonRepeatable() throws Exception { String inputstr = "This is a test message"; byte[] input = inputstr.getBytes("US-ASCII"); InputStream instream = new ByteArrayInputStream(input); RequestEntity requestentity = new InputStreamRequestEntity( instream, InputStreamRequestEntity.CONTENT_LENGTH_AUTO); PostMethod method = new PostMethod("/"); method.setRequestEntity(requestentity); method.setContentChunked(true); UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds)); handlerchain.appendHandler(new HttpServiceHandler(new EchoService())); this.server.setRequestHandler(handlerchain); this.client.getState().setCredentials(AuthScope.ANY, creds); try { this.client.executeMethod(method); fail("ProtocolException should have been thrown"); } catch (ProtocolException ex) { // expected } finally { method.releaseConnection(); } }
private static RequestEntity asRequestEntity(InputStream in, Exchange exchange) throws IOException { if (exchange != null && !exchange.getProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.FALSE, Boolean.class)) { return new InputStreamRequestEntity(GZIPHelper.compressGzip(exchange.getIn() .getHeader(Exchange.CONTENT_ENCODING, String.class), in), ExchangeHelper .getContentType(exchange)); } else { // should set the content type here if (exchange != null) { return new InputStreamRequestEntity(in, ExchangeHelper.getContentType(exchange)); } else { return new InputStreamRequestEntity(in); } } }
private static RequestEntity asRequestEntity(byte[] data, Exchange exchange) throws Exception { if (exchange != null && !exchange.getProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.FALSE, Boolean.class)) { return new InputStreamRequestEntity(GZIPHelper.compressGzip(exchange.getIn() .getHeader(Exchange.CONTENT_ENCODING, String.class), data), ExchangeHelper .getContentType(exchange)); } else { // should set the content type here if (exchange != null) { return new InputStreamRequestEntity(new ByteArrayInputStream(data), ExchangeHelper.getContentType(exchange)); } else { return new InputStreamRequestEntity(new ByteArrayInputStream(data)); } } }
public int executePost(final String url, InputStream input) throws IOException, HttpException { final PostMethod post = new PostMethod(url); assertNotNull(input); final RequestEntity entity = new InputStreamRequestEntity(input, "application/json"); post.setRequestEntity(entity); final HttpClient httpclient = new HttpClient(); int result = -1; try { result = httpclient.executeMethod(post); logger.log(Level.FINE, "Post path: {}", post.getPath()); logger.log(Level.FINE, "Response status code: {}", result); logger.log(Level.FINE, "Response body: {}", post.getResponseBodyAsString()); } finally { // Release current connection to the connection pool once you are done post.releaseConnection(); } return result; }
private String createRequest(final String fileName, final PostMethod httpPost) throws IOException { InputStream inputStream = new FileInputStream(new File(fileName).getAbsoluteFile()); String content = getInputStreamAsString(inputStream); InputStream inputStream2 = new FileInputStream(new File(fileName).getAbsoluteFile()); InputStreamRequestEntity entity = new InputStreamRequestEntity(inputStream2); httpPost.setRequestEntity(entity); return content; }
private static RequestEntity toRequestEntity(Object value) throws PageException { if(value instanceof RequestEntity) return (RequestEntity) value; else if(value instanceof InputStream) { return new InputStreamRequestEntity((InputStream)value,"application/octet-stream"); } else if(Decision.isCastableToBinary(value,false)){ return new ByteArrayRequestEntity(Caster.toBinary(value)); } else { return new StringRequestEntity(Caster.toString(value)); } }
/** * Sets up the given {@link PostMethod} to send the same standard POST data as was sent in the given {@link HttpServletRequest} * * @param postMethodProxyRequest The {@link PostMethod} that we are configuring to send a standard POST request * @param httpServletRequest The {@link HttpServletRequest} that contains the POST data to be sent via the {@link PostMethod} * @throws IOException */ private void handleStandard(EntityEnclosingMethod methodProxyRequest, HttpServletRequest httpServletRequest) throws IOException { try { methodProxyRequest.setRequestEntity(new InputStreamRequestEntity(httpServletRequest.getInputStream())); //LOGGER.info("original request content length:" + httpServletRequest.getContentLength()); //LOGGER.info("proxied request content length:" +methodProxyRequest.getRequestEntity().getContentLength()+""); } catch (IOException e) { throw new IOException(e); } }