List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestEntity
public void setRequestEntity(RequestEntity paramRequestEntity)
From source file:com.apatar.ui.JSubmitHelpDialog.java
private void addListeners() { sendButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { PostMethod filePost = new PostMethod(getUrl()); try { if (!CoreUtils.validEmail(emailField.getText())) { JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "E-mail address is invalid! Please, write a valid e-mail."); return; }//from w w w. j av a 2s .co m List<File> targetFiles = getAttachFile(); List<FilePart> fParts = new ArrayList<FilePart>(); int i = 1; for (File file : targetFiles) { try { fParts.add(new FilePart("file" + i, file)); i++; } catch (java.io.FileNotFoundException ef) { } } int size = fParts.size() + 4; Part[] parts = new Part[size]; parts[0] = new StringPart("BugInformation", text.getText()); parts[1] = new StringPart("FirstName", firstNameField.getText()); parts[2] = new StringPart("LastName", lastNameField.getText()); parts[3] = new StringPart("Email", emailField.getText()); i = 4; for (FilePart fp : fParts) parts[i++] = fp; filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); int status = client.executeMethod(filePost); if (status != HttpStatus.SC_OK) JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "Upload failed, response=" + HttpStatus.getStatusText(status)); else { JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME, "Your message has been sent. Thank you!"); dispose(); } } catch (Exception ex) { ex.printStackTrace(); } finally { filePost.releaseConnection(); } } }); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { dispose(); } }); }
From source file:com.funambol.json.api.dao.FunambolJSONApiDAO.java
protected String sendPostRequest(String REQUEST, String body, long since, long until) throws IOOperationException { String response = null;// ww w. j a v a 2 s. c o m PostMethod method = null; try { HttpClient httpClient = new HttpClient(); method = new PostMethod(REQUEST); addSinceUntil(method, since, until); if (log.isTraceEnabled()) { log.trace("\nREQUEST: " + REQUEST + ""); } if (this.sessionid != null) { method.setRequestHeader("Authorization", this.sessionid); } if (body != null) { byte[] raw = body.getBytes(CHARSET); method.setRequestEntity(new ByteArrayRequestEntity(raw, "text/plain; charset=" + CHARSET)); //method.setRequestContentLength(raw.length); //method.setRequestEntity(new StringRequestEntity(body)); //method.setRequestBody(body); if (log.isTraceEnabled()) { log.trace("body: " + body); } } printHeaderFields(method.getRequestHeaders(), "REQUEST"); int code = httpClient.executeMethod(method); response = method.getResponseBodyAsString(); if (log.isTraceEnabled()) { log.trace("RESPONSE code: " + code); } printHeaderFields(method.getResponseHeaders(), "RESPONSE"); } catch (Exception e) { throw new IOOperationException("Error GET Request ", e); } finally { if (method != null) { method.releaseConnection(); } } return response; }
From source file:com.ihelpoo.app.api.ApiClient.java
/** * post//from w w w . j a v a2 s. c om * * @param url * @param params * @param files * @throws AppException */ private static InputStream _post(AppContext appContext, String url, Map<String, Object> params, Map<String, File> files) throws AppException { //System.out.println("post_url==> "+url); String cookie = getCookie(appContext); String userAgent = getUserAgent(appContext); HttpClient httpClient = null; PostMethod httpPost = null; //post??? int length = (params == null ? 0 : params.size()) + (files == null ? 0 : files.size()); Part[] parts = new Part[length]; int i = 0; if (params != null) for (String name : params.keySet()) { parts[i++] = new StringPart(name, String.valueOf(params.get(name)), UTF_8); } if (files != null) for (String file : files.keySet()) { try { parts[i++] = new FilePart(file, files.get(file)); } catch (FileNotFoundException e) { e.printStackTrace(); } //System.out.println("post_key_file==> "+file); } String responseBody = ""; int time = 0; do { try { httpClient = getHttpClient(); httpPost = getHttpPost(url, cookie, userAgent); httpPost.setRequestEntity(new MultipartRequestEntity(parts, httpPost.getParams())); int statusCode = httpClient.executeMethod(httpPost); if (statusCode != HttpStatus.SC_OK) { throw AppException.http(statusCode); } else if (statusCode == HttpStatus.SC_OK) { Cookie[] cookies = httpClient.getState().getCookies(); String tmpcookies = ""; for (Cookie ck : cookies) { tmpcookies += ck.toString() + ";"; } //?cookie if (appContext != null && tmpcookies != "") { appContext.setProperty("cookie", tmpcookies); appCookie = tmpcookies; } } responseBody = httpPost.getResponseBodyAsString(); // System.out.println("XMLDATA=====>"+responseBody); break; } catch (HttpException e) { time++; if (time < RETRY_TIME) { try { Thread.sleep(1000); } catch (InterruptedException e1) { } continue; } // ????? e.printStackTrace(); throw AppException.http(e); } catch (IOException e) { time++; if (time < RETRY_TIME) { try { Thread.sleep(1000); } catch (InterruptedException e1) { } continue; } // ? e.printStackTrace(); throw AppException.network(e); } finally { // httpPost.releaseConnection(); httpClient = null; } } while (time < RETRY_TIME); responseBody = responseBody.replaceAll("\\p{Cntrl}", ""); // if(responseBody.contains("result") && responseBody.contains("errorCode") && appContext.containsProperty("user.uid")){//FIXME // try { // Result res = Result.parse(new ByteArrayInputStream(responseBody.getBytes())); // if(res.getErrorCode() == 0){ // appContext.logout(); // appContext.getUnLoginHandler().sendEmptyMessage(1); // } // } catch (Exception e) { // e.printStackTrace(); // } // } return new ByteArrayInputStream(responseBody.getBytes()); }
From source file:it.haefelinger.flaka.util.HttpUpload.java
public boolean upload() { File file = null;//from w ww. jav a 2 s . c o m String endpoint = get("endpoint", HttpUpload.ENDPOINT); String testonly = get("testonly", HttpUpload.TESTONLY); String timeout = get("timeout", HttpUpload.TIMEOUT); String filepath = get("filepath", null); String logpath = get("logpath", null); String standard = get("standard", "1.0"); syslog("endpoint: " + endpoint); syslog("testonly: " + testonly); syslog("timeouts: " + timeout); syslog("filepath: " + filepath); syslog("logpath : " + logpath); syslog("standard: " + standard); PostMethod filePost = null; boolean rc; try { /* new game */ rc = false; setError(null); set("logmsg", ""); if (testonly == null || testonly.matches("\\s*false\\s*")) { testonly = "x-do-not-test"; } else { testonly = "test"; } if (filepath == null || filepath.matches("\\s*")) { set("logmsg", "empty property `filepath', nothing to do."); return true; } /* loc to upload */ file = new File(filepath); if (file.exists() == false) { setError("loc `" + file.getPath() + "' does not exist."); return false; } if (file.isFile() == false) { setError("loc `" + file.getPath() + "' exists but not a loc."); return false; } if (file.canRead() == false) { setError("loc `" + file.getPath() + "' can't be read."); return false; } set("filesize", "" + file.length()); /* create HTTP method */ filePost = new PostMethod(endpoint); Part[] parts = { new StringPart(testonly, "(opaque)"), filepart(file) }; filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false); filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); /* execute method */ rc = exec(filePost) && eval(filePost); } finally { /* release resources in just any case */ if (filePost != null) filePost.releaseConnection(); } return rc; }
From source file:com.evolveum.midpoint.model.impl.bulkmodify.PostXML.java
public int createUserForSelfRegistration(ModifyUserBean user) throws Exception { String returnString = ""; int result = 0; // Get target URL String strURLBase = "http://localhost:8080/midpoint/ws/rest/users"; String strURL = strURLBase;/* ww w . j a v a2 s. co m*/ // Prepare HTTP post PostMethod post = new PostMethod(strURL); //AUTHENTICATION String userPass = this.getUsername() + ":" + this.getPassword(); String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userPass.getBytes("UTF-8")); post.addRequestHeader("Authorization", basicAuth); //construct searching string. String sendingXml = XML_TEMPLATE_CREATE_USER_SELFREGISTRATION; sendingXml = sendingXml.replace("<name></name>", "<name>" + user.getUserName() + "</name>"); sendingXml = sendingXml.replace("<givenName></givenName>", "<givenName>" + user.getFirstname() + "</givenName>"); sendingXml = sendingXml.replace("<familyName></familyName>", "<familyName>" + user.getSurname() + "</familyName>"); sendingXml = sendingXml.replace("<emailAddress></emailAddress>", "<emailAddress>" + user.getEmail() + "</emailAddress>"); sendingXml = sendingXml.replace("<telephoneNumber></telephoneNumber>", "<telephoneNumber>" + user.getPhoneNumber() + "</telephoneNumber>"); sendingXml = sendingXml.replace("<administrativeStatus></administrativeStatus>", "<administrativeStatus>" + user.getStatus() + "</administrativeStatus>"); RequestEntity userSearchEntity = new StringRequestEntity(sendingXml, "application/xml", "UTF-8"); post.setRequestEntity(userSearchEntity); // Get HTTP client HttpClient httpclient = new HttpClient(); // Execute request try { result = httpclient.executeMethod(post); // Display status code //System.out.println("Response status code: " + result); // Display response //System.out.println("Response body: "); // System.out.println(post.getResponseBodyAsString()); //String sbf = new String(post.getResponseBodyAsString()); //System.out.println(sbf); } finally { // Release current connection to the connection pool once you are done post.releaseConnection(); } return result; }
From source file:com.sun.faban.driver.transport.hc3.ApacheHC3Transport.java
private void setParameters(PostMethod method, String request) throws UnsupportedEncodingException { // Check whether request is XML or JSON if (request.startsWith("<?xml") || request.startsWith("{")) { Header h = method.getRequestHeader("Content-Type"); if (h == null) { h = method.getRequestHeader("content-type"); }/* w w w .j av a2 s . co m*/ if (h != null) { method.setRequestEntity(new StringRequestEntity(request, h.getValue(), method.getRequestCharSet())); return; } } List<NameValuePair> parameters = new ArrayList<NameValuePair>(); // If none of both, just treat it as html. int idx = 0; if (request == null || request.length() == 0) return; if (request.charAt(0) == '?') ++idx; do { int endIdx = request.indexOf('&', idx); if (endIdx == -1) endIdx = request.length(); int eqIdx = request.indexOf('=', idx); if (eqIdx != -1 && eqIdx < endIdx) { parameters.add( new NameValuePair(request.substring(idx, eqIdx), request.substring(eqIdx + 1, endIdx))); } else { parameters.add(new NameValuePair(request.substring(idx, endIdx), null)); } idx = endIdx + 1; } while (idx < request.length()); method.addParameters(parameters.toArray(new NameValuePair[parameters.size()])); }
From source file:com.zimbra.qa.unittest.TestCalDav.java
@Test public void testXBusyMacAttach() throws ServiceException, IOException { Account dav1 = users[1].create();//w ww. ja v a2 s .c o m String contactsFolderUrl = getFolderUrl(dav1, "Contacts"); HttpClient client = new HttpClient(); PostMethod postMethod = new PostMethod(contactsFolderUrl); addBasicAuthHeaderForUser(postMethod, dav1); postMethod.addRequestHeader("Content-Type", "text/vcard"); postMethod.setRequestEntity( new ByteArrayRequestEntity(smallBusyMacAttach.getBytes(), MimeConstants.CT_TEXT_VCARD)); HttpMethodExecutor exe = HttpMethodExecutor.execute(client, postMethod, HttpStatus.SC_CREATED); String location = null; for (Header hdr : exe.respHeaders) { if ("Location".equals(hdr.getName())) { location = hdr.getValue(); } } assertNotNull("Location Header returned when creating", location); String url = String.format("%s%s", contactsFolderUrl, location.substring(location.lastIndexOf('/') + 1)); GetMethod getMethod = new GetMethod(url); addBasicAuthHeaderForUser(getMethod, dav1); getMethod.addRequestHeader("Content-Type", "text/vcard"); exe = HttpMethodExecutor.execute(client, getMethod, HttpStatus.SC_OK); String respBody = new String(exe.responseBodyBytes, MimeConstants.P_CHARSET_UTF8); String[] expecteds = { "\r\nX-BUSYMAC-ATTACH;X-FILENAME=favicon.ico;ENCODING=B:AAABAAEAEBAAAAEAIABoBA\r\n", "\r\n AAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAQAQAABMLAAATCwAAAAAAAAAAAAAAAAAAw4cAY8\r\n", "\r\nX-BUSYMAC-MODIFIED-BY:Gren Elliot\r\n", "\r\nX-CUSTOM:one two three four five six seven eight nine ten eleven twelve t\r\n hirteen fourteen fifteen", "\r\nX-CUSTOM:Here are my simple\\Nmultiline\\Nnotes\r\n", "\r\nX-CUSTOM;TYPE=pref:semi-colon\\;seperated\\;\"stuff\"\\;here\r\n", "\r\nX-CUSTOM:comma\\,\"stuff\"\\,'there'\\,too\r\n", "\r\nX-HOBBY:my backslash\\\\ hobbies\r\n", "\r\nX-CREATED:2015-04-05T09:50:44Z\r\n" }; for (String expected : expecteds) { assertTrue(String.format("GET should contain '%s'\nBODY=%s", expected, respBody), respBody.contains(expected)); } SearchRequest searchRequest = new SearchRequest(); searchRequest.setSortBy("dateDesc"); searchRequest.setLimit(8); searchRequest.setSearchTypes("contact"); searchRequest.setQuery("in:Contacts"); ZMailbox mbox = users[1].getZMailbox(); SearchResponse searchResp = mbox.invokeJaxb(searchRequest); assertNotNull("JAXB SearchResponse object", searchResp); List<SearchHit> hits = searchResp.getSearchHits(); assertNotNull("JAXB SearchResponse hits", hits); assertEquals("JAXB SearchResponse hits", 1, hits.size()); }
From source file:com.zimbra.qa.unittest.TestCalDav.java
@Test public void testAppleStyleGroup() throws ServiceException, IOException { Account dav1 = users[1].create();/* ww w . jav a2s .c o m*/ String contactsFolderUrl = getFolderUrl(dav1, "Contacts"); HttpClient client = new HttpClient(); PostMethod postMethod = new PostMethod(contactsFolderUrl); addBasicAuthHeaderForUser(postMethod, dav1); postMethod.addRequestHeader("Content-Type", "text/vcard"); postMethod .setRequestEntity(new ByteArrayRequestEntity(rachelVcard.getBytes(), MimeConstants.CT_TEXT_VCARD)); HttpMethodExecutor.execute(client, postMethod, HttpStatus.SC_CREATED); postMethod = new PostMethod(contactsFolderUrl); addBasicAuthHeaderForUser(postMethod, dav1); postMethod.addRequestHeader("Content-Type", "text/vcard"); postMethod.setRequestEntity( new ByteArrayRequestEntity(blueGroupCreate.getBytes(), MimeConstants.CT_TEXT_VCARD)); HttpMethodExecutor exe = HttpMethodExecutor.execute(client, postMethod, HttpStatus.SC_CREATED); String groupLocation = null; for (Header hdr : exe.respHeaders) { if ("Location".equals(hdr.getName())) { groupLocation = hdr.getValue(); } } assertNotNull("Location Header returned when creating Group", groupLocation); postMethod = new PostMethod(contactsFolderUrl); addBasicAuthHeaderForUser(postMethod, dav1); postMethod.addRequestHeader("Content-Type", "text/vcard"); postMethod.setRequestEntity(new ByteArrayRequestEntity(parisVcard.getBytes(), MimeConstants.CT_TEXT_VCARD)); HttpMethodExecutor.execute(client, postMethod, HttpStatus.SC_CREATED); String url = String.format("%s%s", contactsFolderUrl, "F53A6F96-566F-46CC-8D48-A5263FAB5E38.vcf"); PutMethod putMethod = new PutMethod(url); addBasicAuthHeaderForUser(putMethod, dav1); putMethod.addRequestHeader("Content-Type", "text/vcard"); putMethod.setRequestEntity( new ByteArrayRequestEntity(blueGroupModify.getBytes(), MimeConstants.CT_TEXT_VCARD)); HttpMethodExecutor.execute(client, putMethod, HttpStatus.SC_NO_CONTENT); GetMethod getMethod = new GetMethod(url); addBasicAuthHeaderForUser(getMethod, dav1); getMethod.addRequestHeader("Content-Type", "text/vcard"); exe = HttpMethodExecutor.execute(client, getMethod, HttpStatus.SC_OK); String respBody = new String(exe.responseBodyBytes, MimeConstants.P_CHARSET_UTF8); String[] expecteds = { "X-ADDRESSBOOKSERVER-KIND:group", "X-ADDRESSBOOKSERVER-MEMBER:urn:uuid:BE43F16D-336E-4C3E-BAE6-22B8F245A986", "X-ADDRESSBOOKSERVER-MEMBER:urn:uuid:07139DE2-EA7B-46CB-A970-C4DF7F72D9AE" }; for (String expected : expecteds) { assertTrue(String.format("GET should contain '%s'\nBODY=%s", expected, respBody), respBody.contains(expected)); } // members are actually stored in a different way. Make sure it isn't a fluke // that the GET response contained the correct members by checking that the members // appear where expected in a search hit. SearchRequest searchRequest = new SearchRequest(); searchRequest.setSortBy("dateDesc"); searchRequest.setLimit(8); searchRequest.setSearchTypes("contact"); searchRequest.setQuery("in:Contacts"); ZMailbox mbox = users[1].getZMailbox(); SearchResponse searchResp = mbox.invokeJaxb(searchRequest); assertNotNull("JAXB SearchResponse object", searchResp); List<SearchHit> hits = searchResp.getSearchHits(); assertNotNull("JAXB SearchResponse hits", hits); assertEquals("JAXB SearchResponse hits", 3, hits.size()); boolean seenGroup = false; for (SearchHit hit : hits) { ContactInfo contactInfo = (ContactInfo) hit; if ("BlueGroup".equals(contactInfo.getFileAs())) { seenGroup = true; assertEquals("Number of members of group in search hit", 2, contactInfo.getContactGroupMembers().size()); } ZimbraLog.test.info("Hit %s class=%s", hit, hit.getClass().getName()); } assertTrue("Seen group", seenGroup); }
From source file:fr.cls.atoll.motu.processor.wps.framework.WPSFactory.java
/** * Post async./*from ww w . jav a 2s . com*/ * * @param url the url * @param postBody the post body * @param headers the headers * * @return the int * * @throws HttpException the http exception * @throws IOException Signals that an I/O exception has occurred. */ public static int postAsync(String url, InputStream postBody, Map<String, String> headers) throws HttpException, IOException { if (LOG.isDebugEnabled()) { LOG.debug("postAsync(String, InputStream, Map<String,String>) - entering"); } // TODO no proxies used HttpClient client = new HttpClient(); HttpMethodParams httpMethodParams = new HttpMethodParams(); httpMethodParams.setIntParameter(HttpMethodParams.SO_TIMEOUT, 1); PostMethod post = new PostMethod(url); post.setRequestEntity(new InputStreamRequestEntity(postBody)); post.setParams(httpMethodParams); for (String key : headers.keySet()) { post.setRequestHeader(key, headers.get(key)); } int retcode = -1; try { retcode = client.executeMethod(post); } catch (SocketTimeoutException e) { LOG.error("postAsync(String, InputStream, Map<String,String>)", e); // do nothing } if (LOG.isDebugEnabled()) { LOG.debug("postAsync(String, InputStream, Map<String,String>) - exiting"); } return retcode; }
From source file:com.zimbra.qa.unittest.TestCalDav.java
@Test public void testBadPostToSchedulingOutbox() throws Exception { Account dav1 = users[1].create();//from www.j a v a 2 s. c o m Account dav2 = users[2].create(); Account dav3 = users[3].create(); String url = getSchedulingOutboxUrl(dav2, dav2); HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); addBasicAuthHeaderForUser(method, dav2); method.addRequestHeader("Content-Type", "text/calendar"); method.addRequestHeader("Originator", "mailto:" + dav2.getName()); method.addRequestHeader("Recipient", "mailto:" + dav3.getName()); method.setRequestEntity(new ByteArrayRequestEntity(exampleCancelIcal(dav1, dav2, dav3).getBytes(), MimeConstants.CT_TEXT_CALENDAR)); HttpMethodExecutor.execute(client, method, HttpStatus.SC_BAD_REQUEST); }