List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestEntity
public void setRequestEntity(RequestEntity paramRequestEntity)
From source file:demo.jaxrs.search.client.Client.java
private static void uploadToCatalog(final String url, final HttpClient httpClient, final String filename) throws IOException, HttpException { System.out.println("Sent HTTP POST request to upload the file into catalog: " + filename); final PostMethod post = new PostMethod(url); final Part[] parts = { new FilePart(filename, new ByteArrayPartSource(filename, IOUtils.readBytesFromStream(Client.class.getResourceAsStream("/" + filename)))) }; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); try {/*w w w .ja v a 2 s .c o m*/ int status = httpClient.executeMethod(post); if (status == 201) { System.out.println(post.getResponseHeader("Location")); } else if (status == 409) { System.out.println("Document already exists: " + filename); } } finally { post.releaseConnection(); } }
From source file:com.oneapm.base.tools.UrlPostMethod.java
public static void urlPostMethod(String url, String json) { HttpClient httpClient = new HttpClient(); PostMethod method = new PostMethod(url); try {/* w w w . j a v a 2s. c o m*/ if (json != null && !json.trim().equals("")) { RequestEntity requestEntity = new StringRequestEntity(json, "application/x-www-form-urlencoded", "utf-8"); method.setRequestEntity(requestEntity); } long startTime = System.currentTimeMillis(); int x = httpClient.executeMethod(method); long elapsedTime = System.currentTimeMillis(); System.out.println(x + ":" + (elapsedTime - startTime)); } catch (IOException e) { e.printStackTrace(); } finally { method.releaseConnection(); } }
From source file:ca.uvic.cs.tagsea.wizards.TagNetworkSender.java
public static synchronized void send(String xml, IProgressMonitor sendMonitor, int id) throws InvocationTargetException { sendMonitor.beginTask("Uploading Tags", 100); sendMonitor.subTask("Saving Temporary file..."); File location = TagSEAPlugin.getDefault().getStateLocation().toFile(); File temp = new File(location, "tagsea.temp.file.txt"); if (temp.exists()) { String message = "Unable to send tags. Unable to create temporary file."; IOException ex = new IOException(message); throw (new InvocationTargetException(ex, message)); }/*ww w . j a v a 2s . c o m*/ try { FileWriter writer = new FileWriter(temp); writer.write(xml); writer.flush(); writer.close(); } catch (IOException e) { throw new InvocationTargetException(e); } sendMonitor.worked(5); sendMonitor.subTask("Uploading Tags..."); String uploadScript = "http://stgild.cs.uvic.ca/cgi-bin/tagSEAUpload.cgi"; PostMethod post = new PostMethod(uploadScript); String fileName = getToday() + ".txt"; try { Part[] parts = { new StringPart("KIND", "tag"), new FilePart("MYLAR" + id, fileName, temp) }; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); HttpClient client = new HttpClient(); int status = client.executeMethod(post); String resp = getData(post.getResponseBodyAsStream()); if (status != 200) { IOException ex = new IOException(resp); throw (ex); } } catch (IOException e) { throw new InvocationTargetException(e, e.getLocalizedMessage()); } finally { sendMonitor.worked(90); sendMonitor.subTask("Deleting Temporary File"); temp.delete(); sendMonitor.done(); } }
From source file:eu.eco2clouds.api.bonfire.client.rest.RestClient.java
/** * Performs a POST method against the API * @param url -> This URL is going to be converted to API_URL:BONFIRE_PORT/url * @param payload message sent in the post method * @param type specifies the content type of the request * @return Response object encapsulation all the HTTP information, it returns <code>null</code> if there was an error. *//* ww w . jav a2 s . co m*/ public static Response executePostMethod(String url, String username, String password, String payload, String type) { Response response = null; try { PostMethod post = new PostMethod(url); // We define the request entity RequestEntity requestEntity = new StringRequestEntity(payload, type, null); post.setRequestEntity(requestEntity); response = executeMethod(post, BONFIRE_XML, username, password, url); } catch (UnsupportedEncodingException exception) { System.out.println("THE PAYLOAD ENCODING IS NOT SUPPORTED"); System.out.println("ERROR: " + exception.getMessage()); System.out.println("ERROR: " + exception.getStackTrace()); } return response; }
From source file:au.org.ala.spatial.util.UploadSpatialResource.java
/** * sends a PUT or POST call to a URL using authentication and including a * file upload/*from w w w.jav a2s .co m*/ * * @param type one of UploadSpatialResource.PUT for a PUT call or * UploadSpatialResource.POST for a POST call * @param url URL for PUT/POST call * @param username account username for authentication * @param password account password for authentication * @param resourcepath local path to file to upload, null for no file to * upload * @param contenttype file MIME content type * @return server response status code as String or empty String if * unsuccessful */ public static String httpCall(int type, String url, String username, String password, String resourcepath, String contenttype) { String output = ""; HttpClient client = new HttpClient(); client.setConnectionTimeout(10000); client.setTimeout(60000); client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); RequestEntity entity = null; if (resourcepath != null) { File input = new File(resourcepath); entity = new FileRequestEntity(input, contenttype); } HttpMethod call = null; ; if (type == PUT) { PutMethod put = new PutMethod(url); put.setDoAuthentication(true); if (entity != null) { put.setRequestEntity(entity); } call = put; } else if (type == POST) { PostMethod post = new PostMethod(url); if (entity != null) { post.setRequestEntity(entity); } call = post; } else { //SpatialLogger.log("UploadSpatialResource", "invalid type: " + type); return output; } // Execute the request try { int result = client.executeMethod(call); output = result + ": " + call.getResponseBodyAsString(); } catch (Exception e) { //SpatialLogger.log("UploadSpatialResource", "failed upload to: " + url); output = "0: " + e.getMessage(); e.printStackTrace(System.out); } finally { // Release current connection to the connection pool once you are done call.releaseConnection(); } return output; }
From source file:com.sun.faban.harness.webclient.RunUploader.java
/** * Client call to upload the run back to the originating server. * This method does nothing if the run is local. * @param runId The id of the run//from w w w .j a v a 2 s.c o m * @throws IOException If the upload fails */ public static void uploadIfOrigin(String runId) throws IOException { // 1. Check origin File originFile = new File( Config.OUT_DIR + File.separator + runId + File.separator + "META-INF" + File.separator + "origin"); if (!originFile.isFile()) return; // Is local run, do nothing. String originSpec = readStringFromFile(originFile); int idx = originSpec.lastIndexOf('.'); if (idx == -1) { // This is wrong, we do not accept this. logger.severe("Bad origin spec."); return; } idx = originSpec.lastIndexOf('.', idx - 1); if (idx == -1) { logger.severe("Bad origin spec."); return; } String host = originSpec.substring(0, idx); String key = null; URL target = null; String proxyHost = null; int proxyPort = -1; // Search the poll hosts for this origin. for (int i = 0; i < Config.pollHosts.length; i++) { Config.HostInfo pollHost = Config.pollHosts[i]; if (host.equals(pollHost.name)) { key = pollHost.key; target = new URL(pollHost.url, "upload"); proxyHost = pollHost.proxyHost; proxyPort = pollHost.proxyPort; break; } } if (key == null) { logger.severe("Origin host/url/key not found!"); return; } // 2. Jar up the run String[] files = new File(Config.OUT_DIR, runId).list(); File jarFile = new File(Config.TMP_DIR, runId + ".jar"); jar(Config.OUT_DIR + runId, files, jarFile.getAbsolutePath()); // 3. Upload the run ArrayList<Part> params = new ArrayList<Part>(); //MultipartPostMethod post = new MultipartPostMethod(target.toString()); params.add(new StringPart("host", Config.FABAN_HOST)); params.add(new StringPart("key", key)); params.add(new StringPart("origin", "true")); params.add(new FilePart("jarfile", jarFile)); Part[] parts = new Part[params.size()]; parts = params.toArray(parts); PostMethod post = new PostMethod(target.toString()); post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); HttpClient client = new HttpClient(); if (proxyHost != null) client.getHostConfiguration().setProxy(proxyHost, proxyPort); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); int status = client.executeMethod(post); if (status == HttpStatus.SC_FORBIDDEN) logger.severe("Server " + host + " denied permission to upload run " + runId + '!'); else if (status == HttpStatus.SC_NOT_ACCEPTABLE) logger.severe("Run " + runId + " origin error!"); else if (status != HttpStatus.SC_CREATED) logger.severe( "Server responded with status code " + status + ". Status code 201 (SC_CREATED) expected."); jarFile.delete(); }
From source file:com.linkedin.pinot.controller.helix.ControllerTest.java
public static PostMethod sendMultipartPostRequest(String url, String body) throws IOException { HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(url); // our handlers ignore key...so we can put anything here Part[] parts = { new StringPart("body", body) }; postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams())); httpClient.executeMethod(postMethod); return postMethod; }
From source file:com.linkedin.pinot.common.utils.SchemaUtils.java
/** * Given host, port and schema, send a http POST request to upload the {@link Schema}. * * @return <code>true</code> on success. * <P><code>false</code> on failure. *///from w ww .j a va 2 s. co m public static boolean postSchema(@Nonnull String host, int port, @Nonnull Schema schema) { Preconditions.checkNotNull(host); Preconditions.checkNotNull(schema); try { URL url = new URL("http", host, port, "/schemas"); PostMethod httpPost = new PostMethod(url.toString()); try { Part[] parts = { new StringPart(schema.getSchemaName(), schema.toString()) }; MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts, new HttpMethodParams()); httpPost.setRequestEntity(requestEntity); int responseCode = HTTP_CLIENT.executeMethod(httpPost); if (responseCode >= 400) { String response = httpPost.getResponseBodyAsString(); LOGGER.warn("Got error response code: {}, response: {}", responseCode, response); return false; } return true; } finally { httpPost.releaseConnection(); } } catch (Exception e) { LOGGER.error("Caught exception while posting the schema: {} to host: {}, port: {}", schema.getSchemaName(), host, port, e); return false; } }
From source file:com.buglabs.dragonfly.util.WSHelper.java
/** * Refer to/*from w w w .j a v a2 s .c o m*/ * http://lurcher/wiki/index.php/IDE_Web_Service_Interface#Using_a_Token * * @param url * @param token * @param payload * @return * @throws IOException */ protected static String post(String url, String token, String payload) throws IOException { HttpClient c = new HttpClient(); PostMethod m = new PostMethod(url); m.setRequestHeader("Cookie", "token=" + token); m.setRequestEntity(new StringRequestEntity(payload)); c.executeMethod(m); return m.getResponseBodyAsString(); }
From source file:com.utest.domain.service.util.FileUploadUtil.java
public static void uploadFile(final File targetFile, final String targetURL, final String targerFormFieldName_) throws Exception { final PostMethod filePost = new PostMethod(targetURL); filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true); filePost.addRequestHeader("X-Atlassian-Token", "no-check"); try {/*from www.jav a 2s. c om*/ final FilePart fp = new FilePart(targerFormFieldName_, targetFile); fp.setTransferEncoding(null); final Part[] parts = { fp }; filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); final HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); final int status = client.executeMethod(filePost); if (status == HttpStatus.SC_OK) { Logger.getLogger(FileUploadUtil.class) .info("Upload complete, response=" + filePost.getResponseBodyAsString()); } else { Logger.getLogger(FileUploadUtil.class) .info("Upload failed, response=" + HttpStatus.getStatusText(status)); } } catch (final Exception ex) { Logger.getLogger(FileUploadUtil.class) .error("ERROR: " + ex.getClass().getName() + " " + ex.getMessage(), ex); throw ex; } finally { Logger.getLogger(FileUploadUtil.class).debug(new String(filePost.getResponseBody())); filePost.releaseConnection(); } }