List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestBody
public void setRequestBody(NameValuePair[] paramArrayOfNameValuePair) throws IllegalArgumentException
From source file:br.org.acessobrasil.silvinha.util.versoes.AtualizadorDeVersoes.java
public boolean baixarVersao() { HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); NameValuePair param = new NameValuePair("param", "update"); method.setRequestBody(new NameValuePair[] { param }); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); JFrame down = new JFrame("Download"); File downFile = null;//from w w w .j av a2 s. c o m InputStream is = null; FileOutputStream fos = null; try { int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { log.error("Method failed: " + method.getStatusLine()); } Header header = method.getResponseHeader("Content-Disposition"); String fileName = "silvinha.exe"; if (header != null) { fileName = header.getValue().split("=")[1]; } // Read the response body. is = method.getResponseBodyAsStream(); down.pack(); ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(down, TradAtualizadorDeVersoes.FAZ_DOWNLOAD_FILE + fileName, is); pmis.getProgressMonitor().setMinimum(0); pmis.getProgressMonitor().setMaximum((int) method.getResponseContentLength()); downFile = new File(fileName); fos = new FileOutputStream(downFile); int c; while (((c = pmis.read()) != -1) && (!pmis.getProgressMonitor().isCanceled())) { fos.write(c); } fos.flush(); fos.close(); String msgOK = TradAtualizadorDeVersoes.DOWNLOAD_EXITO + TradAtualizadorDeVersoes.DESEJA_ATUALIZAR_EXECUTAR + TradAtualizadorDeVersoes.ARQUIVO_DE_NOME + fileName + TradAtualizadorDeVersoes.LOCALIZADO_NA + TradAtualizadorDeVersoes.PASTA_INSTALACAO + TradAtualizadorDeVersoes.APLICACAO_DEVE_SER_ENCERRADA + TradAtualizadorDeVersoes.DESEJA_CONTINUAR_ATUALIZACAO; if (JOptionPane.showConfirmDialog(null, msgOK, TradAtualizadorDeVersoes.ATUALIZACAO_DO_PROGRAMA, JOptionPane.YES_NO_OPTION) == 0) { return true; } else { return false; } } catch (HttpException he) { log.error("Fatal protocol violation: " + he.getMessage(), he); return false; } catch (InterruptedIOException iioe) { method.abort(); String msg = GERAL.OP_CANCELADA_USUARIO + TradAtualizadorDeVersoes.DIRECIONADO_A_APLICACAO; JOptionPane.showMessageDialog(down, msg); try { if (fos != null) { fos.close(); } } catch (IOException ioe) { method.releaseConnection(); System.exit(0); } if (downFile != null && downFile.exists()) { downFile.delete(); } return false; // System.err.println("Fatal transport error: " + iioe.getMessage()); // iioe.printStackTrace(); } catch (IOException ioe) { log.error("Fatal transport error: " + ioe.getMessage(), ioe); return false; } finally { //Release the connection. method.releaseConnection(); } }
From source file:com.thoughtworks.twist.mingle.core.MingleClient.java
public void attachComment(String taskId, String comment, String description, InputStream createInputStream, String filename, IProgressMonitor monitor) { PostMethod post = new PostMethod(commentUrl(taskId)); NameValuePair[] data = { new NameValuePair("comment", comment), }; post.setRequestBody(data); try {//from w ww. j a va 2s .co m getClient().executeMethod(post); } catch (HttpException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } finally { post.releaseConnection(); } }
From source file:de.suse.swamp.core.util.BugzillaTools.java
private Cookie[] bzConnect(String username, String pwd) throws Exception { Logger.DEBUG("Performing bugzilla login..."); HttpState initialState = new HttpState(); // Do a Login at Bugzilla HttpClient httpclient = new HttpClient(); httpclient.setState(initialState);/*from w w w . j a v a 2 s .c om*/ String loginUrl = swamp.getProperty("BUGZILLA_LOGIN_URL"); // add form fields for logging in: String usernameField = swamp.getProperty("BUGZILLA_LOGIN_FORM_USERNAME"); String passwordField = swamp.getProperty("BUGZILLA_LOGIN_FORM_PWD"); NameValuePair login = new NameValuePair(usernameField, username); NameValuePair pw = new NameValuePair(passwordField, pwd); NameValuePair loginid = new NameValuePair("GoAheadAndLogIn", "1"); PostMethod httppost = new PostMethod(loginUrl); httppost.setRequestBody(new NameValuePair[] { login, pw, loginid }); try { httpclient.executeMethod(httppost); } catch (Exception e) { throw new Exception("Could not connect to " + loginUrl + " (error: " + e.getMessage() + ")"); } Cookie[] cookies = httpclient.getState().getCookies(); //System.out.println("Response: " + httppost.getResponseBodyAsString()); if (cookies == null || cookies.length == 0) { throw new Exception("Could not login to " + loginUrl); } httppost.releaseConnection(); return cookies; }
From source file:com.google.apphosting.vmruntime.jetty9.VmRuntimeJettyKitchenSink2Test.java
/** * Test that blob upload requests are intercepted by the blob upload filter. * * @throws Exception//w ww .j a va 2 s .c o m */ public void testBlobUpload() throws Exception { String postData = "--==boundary\r\n" + "Content-Type: message/external-body; " + "charset=ISO-8859-1; blob-key=\"blobkey:blob-0\"\r\n" + "Content-Disposition: form-data; " + "name=upload-0; filename=\"file-0.jpg\"\r\n" + "\r\n" + "Content-Type: image/jpeg\r\n" + "Content-Length: 1024\r\n" + "X-AppEngine-Upload-Creation: 2009-04-30 17:12:51.675929\r\n" + "Content-Disposition: form-data; " + "name=upload-0; filename=\"file-0.jpg\"\r\n" + "\r\n" + "\r\n" + "--==boundary\r\n" + "Content-Type: text/plain; charset=ISO-8859-1\r\n" + "Content-Disposition: form-data; name=text1\r\n" + "Content-Length: 10\r\n" + "\r\n" + "Testing.\r\n" + "\r\n" + "\r\n" + "--==boundary--"; HttpClient httpClient = new HttpClient(); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000); PostMethod blobPost = new PostMethod(createUrl("/upload-blob").toString()); blobPost.addRequestHeader("Content-Type", "multipart/form-data; boundary=\"==boundary\""); blobPost.addRequestHeader("X-AppEngine-BlobUpload", "true"); blobPost.setRequestBody(postData); int httpCode = httpClient.executeMethod(blobPost); assertEquals(302, httpCode); Header redirUrl = blobPost.getResponseHeader("Location"); assertEquals("http://" + getServerHost() + "/serve-blob?key=blobkey:blob-0", redirUrl.getValue()); }
From source file:com.github.maven.plugin.client.impl.GithubClientImpl.java
public void upload(String artifactName, File file, String description, String repositoryUrl) { assertNotNull(artifactName, "artifactName"); assertNotNull(file, "file"); assertNotNull(repositoryUrl, "repositoryUrl"); assertStartsWith(repositoryUrl, GITHUB_REPOSITORY_URL_PREFIX, "repositoryUrl"); PostMethod githubPost = new PostMethod(toRepositoryDownloadUrl(repositoryUrl)); githubPost.setRequestBody(new NameValuePair[] { new NameValuePair("login", login), new NameValuePair("token", token), new NameValuePair("file_name", artifactName), new NameValuePair("file_size", String.valueOf(file.length())), new NameValuePair("description", description == null ? "" : description) }); try {//from w ww. j a va 2 s . com int response = httpClient.executeMethod(githubPost); if (response == HttpStatus.SC_OK) { ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readValue(githubPost.getResponseBodyAsString(), JsonNode.class); PostMethod s3Post = new PostMethod(GITHUB_S3_URL); Part[] parts = { new StringPart("Filename", artifactName), new StringPart("policy", node.path("policy").getTextValue()), new StringPart("success_action_status", "201"), new StringPart("key", node.path("path").getTextValue()), new StringPart("AWSAccessKeyId", node.path("accesskeyid").getTextValue()), new StringPart("Content-Type", node.path("mime_type").getTextValue()), new StringPart("signature", node.path("signature").getTextValue()), new StringPart("acl", node.path("acl").getTextValue()), new FilePart("file", file) }; MultipartRequestEntity partEntity = new MultipartRequestEntity(parts, s3Post.getParams()); s3Post.setRequestEntity(partEntity); int s3Response = httpClient.executeMethod(s3Post); if (s3Response != HttpStatus.SC_CREATED) { throw new GithubException( "Cannot upload " + file.getName() + " to repository " + repositoryUrl); } s3Post.releaseConnection(); } else if (response == HttpStatus.SC_NOT_FOUND) { throw new GithubRepositoryNotFoundException("Cannot found repository " + repositoryUrl); } else if (response == HttpStatus.SC_UNPROCESSABLE_ENTITY) { throw new GithubArtifactAlreadyExistException( "File " + artifactName + " already exist in " + repositoryUrl + " repository"); } else { throw new GithubException("Error " + HttpStatus.getStatusText(response)); } } catch (IOException e) { throw new GithubException(e); } githubPost.releaseConnection(); }
From source file:com.sun.syndication.propono.atom.client.GDataAuthStrategy.java
private void init() throws ProponoException { try {/*from w w w.j ava2 s .c om*/ HttpClient httpClient = new HttpClient(); PostMethod method = new PostMethod("https://www.google.com/accounts/ClientLogin"); NameValuePair[] data = { new NameValuePair("Email", email), new NameValuePair("Passwd", password), new NameValuePair("accountType", "GOOGLE"), new NameValuePair("service", service), new NameValuePair("source", "ROME Propono Atompub Client") }; method.setRequestBody(data); httpClient.executeMethod(method); String responseBody = method.getResponseBodyAsString(); int authIndex = responseBody.indexOf("Auth="); authToken = "GoogleLogin auth=" + responseBody.trim().substring(authIndex + 5); } catch (Throwable t) { t.printStackTrace(); throw new ProponoException("ERROR obtaining Google authentication string", t); } }
From source file:net.neurowork.cenatic.centraldir.workers.XMLPushTest.java
private void pushOrganization(String token) { PostMethod post = new PostMethod(restUrl.getPushOrganizationUrl()); NameValuePair tokenParam = new NameValuePair("token", token); NameValuePair[] params = new NameValuePair[] { tokenParam }; post.addRequestHeader("Accept", "application/xml"); post.setQueryString(params);/* ww w. j a v a2 s . c o m*/ post.setRequestBody(XmlPushCreator.getInstance().getPushXml(organizacion)); try { int result = httpclient.executeMethod(post); logger.info("Response status code: " + result); logger.info("Response body: "); logger.info(post.getResponseBodyAsString()); } catch (HttpException e) { logger.error(e.getMessage()); } catch (IOException e) { logger.error(e.getMessage()); } finally { post.releaseConnection(); } }
From source file:com.jackbe.mapreduce.RESTClient.java
public void executeREST(String encodedValue) { String result = null;/*www . jav a2 s.c o m*/ String postPath = protocol + host + ":" + port + path; System.out.println("post path = " + postPath); PostMethod pm = new PostMethod(postPath); System.out.println("10 Encoded value = \n" + encodedValue); if (encodedValue != null) { //httpMethod = new PostMethod(protocol + host + ":" + port + path); //InputStream is = new ByteArrayInputStream(encodedValue.getBytes()); //pm.setRequestBody(is); pm.setRequestBody(encodedValue); System.out.println("Validate = " + pm.validate()); //pm.setQueryString(encodedValue); //pm.setHttp11(false); log.debug("Invoking REST service: " + protocol + host + ":" + port + path + " " + pm.toString()); } else { throw new RuntimeException("EncodedValue can't be null"); } try { client.executeMethod(pm); if (pm.getStatusCode() != HttpStatus.SC_OK) { log.error("HTTP Error status connecting to Presto: " + pm.getStatusCode()); log.error("HTTP Error message connecting to Presto: " + pm.getStatusText()); return; } else { if (log.isDebugEnabled()) { log.debug("Status code: " + pm.getStatusCode()); Header contentTypeHeader = pm.getResponseHeader("content-type"); log.debug("Mimetype: " + contentTypeHeader.getValue()); } } result = pm.getResponseBodyAsString(); // log.debug(httpMethod.getStatusText()); if (log.isDebugEnabled()) log.debug("Response: " + result); } catch (Exception e) { log.error("Exception executing REST call: " + e, e); } finally { pm.releaseConnection(); } }
From source file:com.rometools.propono.atom.client.GDataAuthStrategy.java
private void init() throws ProponoException { try {// w ww . j av a 2 s . com final HttpClient httpClient = new HttpClient(); final PostMethod method = new PostMethod("https://www.google.com/accounts/ClientLogin"); final NameValuePair[] data = { new NameValuePair("Email", email), new NameValuePair("Passwd", password), new NameValuePair("accountType", "GOOGLE"), new NameValuePair("service", service), new NameValuePair("source", "ROME Propono Atompub Client") }; method.setRequestBody(data); httpClient.executeMethod(method); final String responseBody = method.getResponseBodyAsString(); final int authIndex = responseBody.indexOf("Auth="); authToken = "GoogleLogin auth=" + responseBody.trim().substring(authIndex + 5); } catch (final Throwable t) { t.printStackTrace(); throw new ProponoException("ERROR obtaining Google authentication string", t); } }
From source file:easyshop.downloadhelper.HttpPageGetter.java
public OriHttpPage getPost(HttpClient client, String action, NameValuePair[] data) { PostMethod post = new PostMethod(action); post.setRequestBody(data); try {//w ww.j av a 2 s .c o m int c = client.executeMethod(post); BufferedInputStream remoteBIS = new BufferedInputStream(post.getResponseBodyAsStream()); ByteArrayOutputStream baos = new ByteArrayOutputStream(10240); byte[] buf = new byte[1024]; int bytesRead = 0; while (bytesRead >= 0) { baos.write(buf, 0, bytesRead); bytesRead = remoteBIS.read(buf); } remoteBIS.close(); byte[] content = baos.toByteArray(); // byte[] content=get.getResponseBody(); ConnResponse conRes = new ConnResponse(post.getResponseHeader("Content-type").getValue(), null, 0, 0, post.getStatusCode()); return new OriHttpPage(action, content, conRes, Constants.CHARTSET_DEFAULT); } catch (IOException ioe) { log.warn("Caught IO Exception: " + ioe.getMessage(), ioe); ioe.printStackTrace(); failureCount++; ConnResponse conRes = new ConnResponse(null, null, 0, 0, 0); return new OriHttpPage(null, null); } }