List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestEntity
public void setRequestEntity(RequestEntity paramRequestEntity)
From source file:com.zimbra.qa.unittest.TestFileUpload.java
private String postAndVerify(ZMailbox mbox, URI uri, boolean clearCookies, String requestId, String attContent) throws IOException { HttpClient client = mbox.getHttpClient(uri); if (clearCookies) { client.getState().clearCookies(); }//from w ww . ja v a2s . c o m List<Part> parts = new ArrayList<Part>(); parts.add(new StringPart("requestId", requestId)); if (attContent != null) { parts.add(mbox.createAttachmentPart("test.txt", attContent.getBytes())); } PostMethod post = new PostMethod(uri.toString()); post.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams())); int status = HttpClientUtil.executeMethod(client, post); assertEquals(200, status); String contentType = getHeaderValue(post, "Content-Type"); assertTrue(contentType, contentType.startsWith("text/html")); String content = post.getResponseBodyAsString(); post.releaseConnection(); return content; }
From source file:eu.europa.ec.markt.dss.validation.https.CommonsHttpDataLoader.java
@Override public InputStream post(String URL, InputStream content) throws CannotFetchDataException { try {//from w w w .ja v a 2 s .c o m LOG.fine("Post data to url " + URL); PostMethod post = new PostMethod(URL); RequestEntity requestEntity = new InputStreamRequestEntity(content); post.setRequestEntity(requestEntity); if (contentType != null) { post.setRequestHeader("Content-Type", contentType); } getClient().executeMethod(post); return post.getResponseBodyAsStream(); } catch (IOException ex) { throw new CannotFetchDataException(ex, URL); } }
From source file:com.voa.weixin.task.UpdateFileTask.java
@Override public void run() { logger.debug("updatefile url :" + this.url); generateUrl();/*from w w w . j av a 2s . co m*/ PostMethod filePost = new PostMethod(url); try { Part[] parts = { new FilePart(updateFile.getName(), updateFile) }; filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); int status = client.executeMethod(filePost); WeixinResult result = new WeixinResult(); if (status == 200) { String responseStr = filePost.getResponseBodyAsString(); logger.debug(responseStr); result.setJson(responseStr); } else { result.setErrMsg("uplaod file weixin request error , http status : " + status); } callbackWork(result); } catch (Exception e) { e.printStackTrace(LogUtil.getErrorStream(logger)); throw new WorkException("update file error.", e); } finally { filePost.releaseConnection(); } }
From source file:com.nokia.carbide.internal.bugreport.model.Communication.java
/** * Sends given fields as a bug_report to the server provided by product. * @param fields values which are sent to the server * @param product product provides e.g. server URL * @return bug_id of the added bug_entry * @throws RuntimeException if an error occurred. Error can be either some communication error * or error message provided by the server (e.g. invalid password) *///from w ww . j a v a 2 s . co m public static String sendBugReport(Hashtable<String, String> fields, IProduct product) throws RuntimeException { // Nothing to send if (fields == null || fields.size() < 1) { throw new RuntimeException(Messages.getString("Communication.NothingToSend")); //$NON-NLS-1$ } String bugNumber = ""; //$NON-NLS-1$ String url = product.getUrl(); if (url.startsWith("https")) { //$NON-NLS-1$ // we'll support HTTPS with trusted (i.e. signed) certificates // Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"); //$NON-NLS-1$ //$NON-NLS-2$ } PostMethod filePost = new PostMethod(url); Part[] parts = new Part[fields.size()]; int i = 0; Iterator<Map.Entry<String, String>> it = fields.entrySet().iterator(); // create parts while (it.hasNext()) { Map.Entry<String, String> productField = it.next(); // attachment field if (productField.getKey() == FieldsHandler.FIELD_ATTACHMENT) { File f = new File(productField.getValue()); try { parts[i] = new FilePart(FieldsHandler.FIELD_DATA, f); } catch (FileNotFoundException e) { e.printStackTrace(); parts[i] = new StringPart(FieldsHandler.FIELD_DATA, Messages.getString("Communication.NotFound")); //$NON-NLS-1$ } // string field } else { parts[i] = new StringPart(productField.getKey(), productField.getValue()); } i++; } filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(8000); setProxyData(client, filePost); int status = 0; String receivedData = ""; //$NON-NLS-1$ try { status = client.executeMethod(filePost); receivedData = filePost.getResponseBodyAsString(1024 * 1024); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } finally { filePost.releaseConnection(); } // HTTP status codes: 2xx = Success if (status >= 200 && status < 300) { // some error occurred in the server side (e.g. invalid password) if (receivedData.contains(FieldsHandler.TAG_RESPONSE_ERROR) && receivedData.contains(FieldsHandler.TAG_RESPONSE_ERROR_CLOSE)) { int beginIndex = receivedData.indexOf(FieldsHandler.TAG_RESPONSE_ERROR) + FieldsHandler.TAG_RESPONSE_ERROR.length(); int endIndex = receivedData.indexOf(FieldsHandler.TAG_RESPONSE_ERROR_CLOSE); String error = receivedData.substring(beginIndex, endIndex); error = error.trim(); throw new RuntimeException(error); // bug_entry was added successfully to database, read the bug_number } else if (receivedData.contains(FieldsHandler.TAG_RESPONSE_BUG_ID) && receivedData.contains(FieldsHandler.TAG_RESPONSE_BUG_ID_CLOSE)) { int beginIndex = receivedData.indexOf(FieldsHandler.TAG_RESPONSE_BUG_ID) + FieldsHandler.TAG_RESPONSE_BUG_ID.length(); int endIndex = receivedData.indexOf(FieldsHandler.TAG_RESPONSE_BUG_ID_CLOSE); bugNumber = receivedData.substring(beginIndex, endIndex); bugNumber = bugNumber.trim(); // some unknown error } else { throw new RuntimeException(Messages.getString("Communication.UnknownError")); //$NON-NLS-1$ } // some HTTP error (status code other than 2xx) } else { String error = Messages.getString("Communication.HttpError") + status; //$NON-NLS-1$ throw new RuntimeException(error); } return bugNumber; }
From source file:com.epam.wilma.service.http.WilmaHttpClient.java
/** * Posting the given file to the given URL via HTTP POST method and returns * {@code true} if the request was successful. * * @param url the given URL/*from w ww .java 2s .c o m*/ * @param file the given file * @return {@code true} if the request is successful, otherwise return {@code false} */ public boolean uploadFile(String url, File file) { boolean requestSuccessful = false; PostMethod method = new PostMethod(url); try { Part[] parts = { new FilePart("file", file) }; method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); int statusCode = httpclient.executeMethod(method); if (HttpStatus.SC_OK == statusCode) { requestSuccessful = true; } } catch (HttpException e) { LOG.error("Protocol exception occurred when called: " + url, e); } catch (IOException e) { LOG.error("I/O (transport) error occurred when called: " + url, e); } finally { method.releaseConnection(); } return requestSuccessful; }
From source file:de.bermuda.arquillian.example.ContentTypeProxyTest.java
private PostMethod postRequest(String body, String localPath) { HttpClient client = new HttpClient(); PostMethod postMethod = new PostMethod(BASE_URL + "/proxy" + localPath); try {//from w w w.j a v a 2 s .c o m StringRequestEntity entity = new StringRequestEntity(body, "application/soap+xml", "UTF-8"); postMethod.setRequestEntity(entity); } catch (IOException e) { Assert.assertTrue("Catched IOException", false); } try { int status = client.executeMethod(postMethod); Assert.assertEquals("Expected OK", status, HttpStatus.SC_OK); } catch (HttpException e) { Assert.assertFalse("HttpException", true); } catch (IOException e) { Assert.assertFalse("IOException", true); } return postMethod; }
From source file:com.sun.faban.harness.util.CLI.java
private void doPostSubmit(String master, String user, String password, ArrayList<String> argList) throws IOException { String url = master + argList.get(0) + '/' + argList.get(1) + '/' + argList.get(2); ArrayList<Part> params = new ArrayList<Part>(); if (user != null) params.add(new StringPart("sun", user)); if (password != null) params.add(new StringPart("sp", password)); int submitCount = 0; for (int i = 3; i < argList.size(); i++) { File configFile = new File(argList.get(i)); if (configFile.isFile()) { params.add(new FilePart("configfile", configFile)); ++submitCount;//from ww w .ja va 2 s .c o m } else { System.err.println("File " + argList.get(i) + " not found."); } } if (submitCount == 0) { throw new IOException("No run submitted!"); } Part[] parts = new Part[params.size()]; parts = params.toArray(parts); PostMethod post = new PostMethod(url); post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); makeRequest(post); }
From source file:com.hw13c.HttpClientPost.java
private void postFile(File file, PostMethod method) throws IOException { method.setRequestEntity(new FileRequestEntity(file, null)); doRequest(file, method);/* w w w . j av a 2 s .c om*/ }
From source file:com.predic8.membrane.integration.ViaProxyTest.java
@Test public void testPost() throws Exception { HttpClient client = new HttpClient(); PostMethod post = new PostMethod("http://localhost:4000/axis2/services/BLZService"); InputStream stream = this.getClass().getResourceAsStream("/getBank.xml"); InputStreamRequestEntity entity = new InputStreamRequestEntity(stream); post.setRequestEntity(entity); post.setRequestHeader(Header.CONTENT_TYPE, MimeType.TEXT_XML_UTF8); post.setRequestHeader(Header.SOAP_ACTION, ""); assertEquals(200, client.executeMethod(post)); }
From source file:net.morphbank.mbsvc3.test.SendImageTest.java
public void sendImage(String strURL, String id, String originalFileName, String imageFileName) throws Exception { File input = new File(imageFileName); // Prepare HTTP post PostMethod post = new PostMethod(strURL); Part[] parts = { new StringPart("id", id), new StringPart("fileName", originalFileName), new FilePart("image", originalFileName, input) }; RequestEntity entity = new MultipartRequestEntity(parts, post.getParams()); post.setRequestEntity(entity); // Get HTTP client HttpClient httpclient = new HttpClient(); // Execute request try {/*from w ww. j av a 2s . c o m*/ System.out.println("Trying post"); int result = httpclient.executeMethod(post); // Display status code System.out.println("Response status code: " + result); // Display response System.out.println("Response body: "); InputStream response = post.getResponseBodyAsStream(); // int j = response.read(); System.out.write(j); for (int i = response.read(); i != -1; i = response.read()) { System.out.write(i); } // System.out.flush(); } finally { // Release current connection to the connection pool once you are // done post.releaseConnection(); } }