List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestEntity
public void setRequestEntity(RequestEntity paramRequestEntity)
From source file:net.sf.antcontrib.net.httpclient.PostMethodTask.java
protected void configureMethod(HttpMethodBase method) { PostMethod post = (PostMethod) method; if (parts.size() == 1 && !multipart) { Object part = parts.get(0); if (part instanceof FilePartType) { FilePartType filePart = (FilePartType) part; try { stream = new FileInputStream(filePart.getPath().getAbsolutePath()); post.setRequestEntity(new InputStreamRequestEntity(stream, filePart.getPath().length(), filePart.getContentType())); } catch (IOException e) { throw new BuildException(e); }/*from w w w .ja v a 2 s . c o m*/ } else if (part instanceof TextPartType) { TextPartType textPart = (TextPartType) part; try { post.setRequestEntity(new StringRequestEntity(textPart.getValue(), textPart.getContentType(), textPart.getCharSet())); } catch (UnsupportedEncodingException e) { throw new BuildException(e); } } } else if (!parts.isEmpty()) { Part partArray[] = new Part[parts.size()]; for (int i = 0; i < parts.size(); i++) { Object part = parts.get(i); if (part instanceof FilePartType) { FilePartType filePart = (FilePartType) part; try { partArray[i] = new FilePart(filePart.getPath().getName(), filePart.getPath().getName(), filePart.getPath(), filePart.getContentType(), filePart.getCharSet()); } catch (FileNotFoundException e) { throw new BuildException(e); } } else if (part instanceof TextPartType) { TextPartType textPart = (TextPartType) part; partArray[i] = new StringPart(textPart.getName(), textPart.getValue(), textPart.getCharSet()); ((StringPart) partArray[i]).setContentType(textPart.getContentType()); } } MultipartRequestEntity entity = new MultipartRequestEntity(partArray, post.getParams()); post.setRequestEntity(entity); } }
From source file:com.zimbra.cs.zimlet.ProxyServlet.java
private void doProxy(HttpServletRequest req, HttpServletResponse resp) throws IOException { ZimbraLog.clearContext();/* w ww . j a v a 2 s . co m*/ boolean isAdmin = isAdminRequest(req); AuthToken authToken = isAdmin ? getAdminAuthTokenFromCookie(req, resp, true) : getAuthTokenFromCookie(req, resp, true); if (authToken == null) { String zAuthToken = req.getParameter(QP_ZAUTHTOKEN); if (zAuthToken != null) { try { authToken = AuthProvider.getAuthToken(zAuthToken); if (authToken.isExpired()) { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken expired"); return; } if (!authToken.isRegistered()) { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken is invalid"); return; } if (isAdmin && !authToken.isAdmin()) { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "permission denied"); return; } } catch (AuthTokenException e) { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "unable to parse authtoken"); return; } } } if (authToken == null) { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "no authtoken cookie"); return; } // get the posted body before the server read and parse them. byte[] body = copyPostedData(req); // sanity check String target = req.getParameter(TARGET_PARAM); if (target == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } // check for permission URL url = new URL(target); if (!isAdmin && !checkPermissionOnTarget(url, authToken)) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } // determine whether to return the target inline or store it as an upload String uploadParam = req.getParameter(UPLOAD_PARAM); boolean asUpload = uploadParam != null && (uploadParam.equals("1") || uploadParam.equalsIgnoreCase("true")); HttpMethod method = null; try { HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient(); HttpProxyUtil.configureProxy(client); String reqMethod = req.getMethod(); if (reqMethod.equalsIgnoreCase("GET")) { method = new GetMethod(target); } else if (reqMethod.equalsIgnoreCase("POST")) { PostMethod post = new PostMethod(target); if (body != null) post.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType())); method = post; } else if (reqMethod.equalsIgnoreCase("PUT")) { PutMethod put = new PutMethod(target); if (body != null) put.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType())); method = put; } else if (reqMethod.equalsIgnoreCase("DELETE")) { method = new DeleteMethod(target); } else { ZimbraLog.zimlet.info("unsupported request method: " + reqMethod); resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } // handle basic auth String auth, user, pass; auth = req.getParameter(AUTH_PARAM); user = req.getParameter(USER_PARAM); pass = req.getParameter(PASS_PARAM); if (auth != null && user != null && pass != null) { if (!auth.equals(AUTH_BASIC)) { ZimbraLog.zimlet.info("unsupported auth type: " + auth); resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } HttpState state = new HttpState(); state.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass)); client.setState(state); method.setDoAuthentication(true); } Enumeration headers = req.getHeaderNames(); while (headers.hasMoreElements()) { String hdr = (String) headers.nextElement(); ZimbraLog.zimlet.debug("incoming: " + hdr + ": " + req.getHeader(hdr)); if (canProxyHeader(hdr)) { ZimbraLog.zimlet.debug("outgoing: " + hdr + ": " + req.getHeader(hdr)); if (hdr.equalsIgnoreCase("x-host")) method.getParams().setVirtualHost(req.getHeader(hdr)); else method.addRequestHeader(hdr, req.getHeader(hdr)); } } try { if (!(reqMethod.equalsIgnoreCase("POST") || reqMethod.equalsIgnoreCase("PUT"))) { method.setFollowRedirects(true); } HttpClientUtil.executeMethod(client, method); } catch (HttpException ex) { ZimbraLog.zimlet.info("exception while proxying " + target, ex); resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } int status = method.getStatusLine() == null ? HttpServletResponse.SC_INTERNAL_SERVER_ERROR : method.getStatusCode(); // workaround for Alexa Thumbnails paid web service, which doesn't bother to return a content-type line Header ctHeader = method.getResponseHeader("Content-Type"); String contentType = ctHeader == null || ctHeader.getValue() == null ? DEFAULT_CTYPE : ctHeader.getValue(); InputStream targetResponseBody = method.getResponseBodyAsStream(); if (asUpload) { String filename = req.getParameter(FILENAME_PARAM); if (filename == null || filename.equals("")) filename = new ContentType(contentType).getParameter("name"); if ((filename == null || filename.equals("")) && method.getResponseHeader("Content-Disposition") != null) filename = new ContentDisposition(method.getResponseHeader("Content-Disposition").getValue()) .getParameter("filename"); if (filename == null || filename.equals("")) filename = "unknown"; List<Upload> uploads = null; if (targetResponseBody != null) { try { Upload up = FileUploadServlet.saveUpload(targetResponseBody, filename, contentType, authToken.getAccountId()); uploads = Arrays.asList(up); } catch (ServiceException e) { if (e.getCode().equals(MailServiceException.UPLOAD_REJECTED)) status = HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE; else status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; } } resp.setStatus(status); FileUploadServlet.sendResponse(resp, status, req.getParameter(FORMAT_PARAM), null, uploads, null); } else { resp.setStatus(status); resp.setContentType(contentType); for (Header h : method.getResponseHeaders()) if (canProxyHeader(h.getName())) resp.addHeader(h.getName(), h.getValue()); if (targetResponseBody != null) ByteUtil.copy(targetResponseBody, true, resp.getOutputStream(), true); } } finally { if (method != null) method.releaseConnection(); } }
From source file:edu.mit.lib.tools.Modernize.java
private void uploadPackage(Path pkg, String targetUri) throws IOException { // using older Apache http client library to make compatible with more systems PostMethod post = new PostMethod(targetUri); HttpClient client = new HttpClient(); RequestEntity entity = new FileRequestEntity(pkg.toFile(), "application/zip"); post.setRequestEntity(entity); try {//from w ww .j av a 2 s. co m int result = client.executeMethod(post); } finally { post.releaseConnection(); } }
From source file:com.cloud.network.bigswitch.BigSwitchVnsApi.java
protected <T> void executeCreateObject(T newObject, Type returnObjectType, String uri, Map<String, String> parameters) throws BigSwitchVnsApiException { if (_host == null || _host.isEmpty()) { throw new BigSwitchVnsApiException("Hostname is null or empty"); }/* w ww . ja va 2 s . co m*/ Gson gson = new Gson(); PostMethod pm = (PostMethod) createMethod("post", uri, 80); pm.setRequestHeader(CONTENT_TYPE, CONTENT_JSON); pm.setRequestHeader(ACCEPT, CONTENT_JSON); pm.setRequestHeader(HTTP_HEADER_INSTANCE_ID, CLOUDSTACK_INSTANCE_ID); try { pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), CONTENT_JSON, null)); } catch (UnsupportedEncodingException e) { throw new BigSwitchVnsApiException("Failed to encode json request body", e); } executeMethod(pm); if (pm.getStatusCode() != HttpStatus.SC_OK) { String errorMessage = responseToErrorMessage(pm); pm.releaseConnection(); s_logger.error("Failed to create object : " + errorMessage); throw new BigSwitchVnsApiException("Failed to create object : " + errorMessage); } pm.releaseConnection(); return; }
From source file:com._17od.upm.transport.HTTPTransport.java
public void put(String targetLocation, File file, String username, String password) throws TransportException { targetLocation = addTrailingSlash(targetLocation) + "upload.php"; PostMethod post = new PostMethod(targetLocation); //This part is wrapped in a try/finally so that we can ensure //the connection to the HTTP server is always closed cleanly try {//from w w w.j av a2s . c o m Part[] parts = { new FilePart("userfile", file) }; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); //Set the HTTP authentication details if (username != null) { Credentials creds = new UsernamePasswordCredentials(new String(username), new String(password)); URL url = new URL(targetLocation); AuthScope authScope = new AuthScope(url.getHost(), url.getPort()); client.getState().setCredentials(authScope, creds); client.getParams().setAuthenticationPreemptive(true); } // This line makes the HTTP call int status = client.executeMethod(post); // I've noticed on Windows (at least) that PHP seems to fail when moving files on the first attempt // The second attempt works so lets just do that if (status == HttpStatus.SC_OK && post.getResponseBodyAsString().equals("FILE_WASNT_MOVED")) { status = client.executeMethod(post); } if (status != HttpStatus.SC_OK) { throw new TransportException( "There's been some kind of problem uploading a file to the HTTP server.\n\nThe HTTP error message is [" + HttpStatus.getStatusText(status) + "]"); } if (!post.getResponseBodyAsString().equals("OK")) { throw new TransportException( "There's been some kind of problem uploading a file to the HTTP server.\n\nThe error message is [" + post.getResponseBodyAsString() + "]"); } } catch (FileNotFoundException e) { throw new TransportException(e); } catch (MalformedURLException e) { throw new TransportException(e); } catch (HttpException e) { throw new TransportException(e); } catch (IOException e) { throw new TransportException(e); } finally { post.releaseConnection(); } }
From source file:de.bermuda.arquillian.example.ContentTypeProxyServlet.java
private void copyRequestBody(HttpServletRequest req, PostMethod post) throws IOException { BufferedReader contentReader = req.getReader(); StringBuilder content = new StringBuilder(); String contentLine = ""; while (contentLine != null) { content.append(contentLine);//from w w w . j av a 2 s .co m contentLine = contentReader.readLine(); } StringRequestEntity requestEntity = new StringRequestEntity(content.toString(), req.getContentType(), req.getCharacterEncoding()); post.setRequestEntity(requestEntity); requestLogger.info("RequestBody: " + content); }
From source file:jeeves.utils.XmlRequest.java
/** Sends the content of a file using a POST request and gets the response in * xml format.//www .j a v a 2 s . co m */ public Element send(String name, File inFile) throws IOException, BadXmlResponseEx, BadSoapResponseEx { Part[] parts = new Part[alSimpleParams.size() + 1]; int partsIndex = 0; parts[partsIndex] = new FilePart(name, inFile); for (NameValuePair nv : alSimpleParams) parts[++partsIndex] = new StringPart(nv.getName(), nv.getValue()); PostMethod post = new PostMethod(); post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); post.addRequestHeader("Accept", !useSOAP ? "application/xml" : "application/soap+xml"); post.setPath(address); post.setDoAuthentication(useAuthent()); //--- execute request Element response = doExecute(post); if (useSOAP) response = soapUnembed(response); return response; }
From source file:eu.learnpad.cw.CWXwikiBridge.java
License:asdf
private void loadPackage(InputStream packageStream) { // Now send the package's path to the importer for XWiki HttpClient httpClient = restResource.getClient(); String uri = DefaultRestResource.REST_URI + "/wikis/xwiki/xff"; PostMethod postMethod = new PostMethod(uri); postMethod.addRequestHeader("Accept", "application/octet-stream"); RequestEntity packageEntity = new InputStreamRequestEntity(packageStream); postMethod.setRequestEntity(packageEntity); try {/*from w w w . j a v a 2 s . c om*/ httpClient.executeMethod(postMethod); } catch (IOException e) { String message = "Unable to upload the XFF package"; logger.error(message, e); } }
From source file:de.extra.client.plugins.outputplugin.transport.ExtraTransportHttp.java
/** * ExtrasTransportHttp is an implementation of IExtraTransport and provides * Communication via http(s) protocol./*from w ww. j a v a 2s .c om*/ * * @see de.extra.client.transport.IExtraTransport#senden(java.lang.String) */ @Override public InputStream senden(final InputStream extraRequest) throws ExtraTransportException { if (client != null) { // Init response InputStream extraResponse = null; // Build url String and create post request PostMethod method = new PostMethod(requestURL); try { RequestEntity entity = new InputStreamRequestEntity(extraRequest); method.setRequestEntity(entity); // Execute the method - send it int statusCode = client.executeMethod(method); // Something goes wrong if (statusCode != HttpStatus.SC_OK) { throw new ExtraTransportException( "Versand von Request fehlgeschlagen: " + method.getStatusLine()); } else { // Read the response body and save it extraResponse = method.getResponseBodyAsStream(); } } catch (HttpException e) { throw new ExtraTransportException("Schwere Protokollverletzung: " + e.getMessage(), e); } catch (IOException e) { throw new ExtraTransportException("Schwerer Transportfehler: " + e.getMessage(), e); } finally { // Release the connection. method.releaseConnection(); } return extraResponse; } else { throw new ExtraTransportException("Http Client nicht initialisiert!"); } }
From source file:edu.wustl.bulkoperator.client.BulkOperationServiceImpl.java
/** * This method will be called to start the bulk operation. * @param operationName operation name./*from w w w . j a va 2s.c om*/ * @param csvFile CSV file. * @param xmlTemplateFile XML template file. * @return Job Message. * @throws BulkOperationException BulkOperationException */ public JobMessage startbulkOperation(String operationName, File csvFile, File xmlTemplateFile) throws BulkOperationException { JobMessage jobMessage = null; if (!isLoggedIn) { jobMessage = new JobMessage(); jobMessage.setOperationSuccessfull(false); jobMessage.addMessage(ApplicationProperties.getValue("bulk.operation.client.login.error")); return jobMessage; } PostMethod postMethod = new PostMethod(url + "/BulkHandler.do"); try { Part[] parts = { new StringPart(OPERATION, operationName), new FilePart(TEMPLATE_FILE, xmlTemplateFile), new FilePart(CSV_FILE, csvFile) }; postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams())); client.executeMethod(postMethod); InputStream inputStream = (InputStream) postMethod.getResponseBodyAsStream(); ObjectInputStream oist = new ObjectInputStream(inputStream); Object object = oist.readObject(); jobMessage = (JobMessage) object; } catch (FileNotFoundException exp) { List<String> listOfArguments = new ArrayList<String>(); listOfArguments.add(xmlTemplateFile.getName()); listOfArguments.add(csvFile.getName()); jobMessage = new JobMessage(); jobMessage.setOperationSuccessfull(false); jobMessage.addMessage(ApplicationProperties.getValue("bulk.operation.file.not.found", listOfArguments)); } catch (IOException e) { List<String> listOfArguments = new ArrayList<String>(); listOfArguments.add(xmlTemplateFile.getName()); listOfArguments.add(csvFile.getName()); jobMessage = new JobMessage(); jobMessage.setOperationSuccessfull(false); jobMessage.addMessage(ApplicationProperties.getValue("bulk.operation.file.not.found", listOfArguments)); } catch (ClassNotFoundException e) { jobMessage = new JobMessage(); jobMessage.setOperationSuccessfull(false); jobMessage.addMessage(ApplicationProperties.getValue("clz.not.found.error")); } finally { postMethod.releaseConnection(); } return jobMessage; }