List of usage examples for org.apache.commons.httpclient.methods PostMethod addParameter
public void addParameter(NameValuePair paramNameValuePair) throws IllegalArgumentException
From source file:org.mule.transport.http.functional.HttpPersistentQueueTestCase.java
@Test public void testPersistentMessageDeliveryWithPost() throws Exception { PostMethod method = new PostMethod("http://localhost:" + port + "/services/Echo"); method.addRequestHeader(HttpConstants.HEADER_CONNECTION, "close"); method.addParameter(new NameValuePair("foo", "bar")); doTestPersistentMessageDelivery(method); }
From source file:org.pegadi.client.ApplicationLauncher.java
public boolean webLogin(String url, String user, String pass) { log.info("Weblogin with url {}", url); PostMethod post = new PostMethod(url + "j_security_check"); post.addParameter(new NameValuePair("j_username", user)); post.addParameter(new NameValuePair("j_password", pass)); try {/* www . java 2 s. co m*/ LoginContext.httpClient.executeMethod(post); } catch (IOException e) { log.error("Error executing method for weblogin", e); return false; } return true; }
From source file:org.ramadda.util.HttpFormField.java
/** * _more_//from w w w . jav a 2 s .com * * @param entries _more_ * @param urlPath _more_ * * @return _more_ */ private static PostMethod getMethod(List entries, String urlPath) { PostMethod postMethod = new PostMethod(urlPath); boolean anyFiles = false; int count = 0; List goodEntries = new ArrayList(); for (int i = 0; i < entries.size(); i++) { HttpFormField formEntry = (HttpFormField) entries.get(i); if (!formEntry.okToPost()) { continue; } goodEntries.add(entries.get(i)); if (formEntry.type == TYPE_FILE) { anyFiles = true; } } if (anyFiles) { Part[] parts = new Part[goodEntries.size()]; for (int i = 0; i < goodEntries.size(); i++) { HttpFormField formEntry = (HttpFormField) goodEntries.get(i); if (formEntry.type == TYPE_FILE) { parts[i] = formEntry.getFilePart(); } else { //Not sure why but we have seen a couple of times //the byte value '0' gets into one of these strings //This causes an error in the StringPart. // System.err.println(" String value = formEntry.getValue(); char with = new String(" ").charAt(0); while (value.indexOf(0) >= 0) { value = value.replace((char) 0, with); } parts[i] = new StringPart(formEntry.getName(), value); } } postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams())); } else { for (int i = 0; i < goodEntries.size(); i++) { HttpFormField formEntry = (HttpFormField) goodEntries.get(i); postMethod.addParameter(new NameValuePair(formEntry.getName(), formEntry.getValue())); } } return postMethod; }
From source file:org.wise.vle.web.RApacheController.java
/** * Handle requests to the RApache server * @param request/*from w ww . j a v a 2 s . c om*/ * @param response * @throws IOException * @throws ServletException * @throws JSONException */ private void handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { HttpClient client = new HttpClient(); String targetURL = null; String rtype = null; try { vleProperties = new Properties(); vleProperties.load(getClass().getClassLoader().getResourceAsStream("vle.properties")); targetURL = vleProperties.getProperty("rApache_url"); rtype = request.getParameter("type"); } catch (Exception e) { System.err .println("RApacheController could not locate the rApache URL and/or identify the request type"); e.printStackTrace(); } if (targetURL != null && rtype != null) { // Create a method instance. if (rtype.equals("rstat")) { PostMethod method = new PostMethod(targetURL); String rdata = request.getParameter("rdata"); // Map input = request.getParameterMap(); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); method.addParameter(new NameValuePair("rtype", rtype)); method.addParameter(new NameValuePair("rdata", rdata)); byte[] responseBody = null; try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + method.getStatusLine()); } // Read the response body. responseBody = method.getResponseBody(); // Deal with the response. // Use caution: ensure correct character encoding and is not binary data } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // Release the connection. method.releaseConnection(); } String responseString = ""; if (responseBody != null) { responseString = new String(responseBody); } try { response.getWriter().print(responseString); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { PostMethod method = new PostMethod(targetURL); String rdata = request.getParameter("rdata"); rdata = URLDecoder.decode(rdata, "UTF-8"); // Map input = request.getParameterMap(); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); method.addParameter(new NameValuePair("rtype", rtype)); method.addParameter(new NameValuePair("rdata", rdata)); byte[] responseBody = null; try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + method.getStatusLine()); } // Read the response body. responseBody = method.getResponseBody(); // Deal with the response. // Use caution: ensure correct character encoding and is not binary data } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // Release the connection. method.releaseConnection(); } try { ServletOutputStream out = response.getOutputStream(); response.setContentType("image/jpeg"); response.setContentLength(responseBody.length); out.write(responseBody, 0, responseBody.length); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
From source file:org.wso2.iot.firealarm.access.api.AccessTokenClient.java
public AccessTokenInfo getAccessToken(String username, String password, String appInstanceId) throws AccessTokenException { SSLContext ctx;//from www . j a v a 2s . com String response = ""; try { ctx = SSLContext.getInstance("TLS"); ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom()); SSLContext.setDefault(ctx); URL url = new URL(tokenURL); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String arg0, SSLSession arg1) { return true; } }); //System.out.println(conn.getResponseCode()); conn.disconnect(); HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(tokenURL); postMethod.addParameter(new NameValuePair("grant_type", grantType)); postMethod.addParameter(new NameValuePair("username", username)); postMethod.addParameter(new NameValuePair("password", password)); postMethod.addParameter(new NameValuePair("scope", scope + appInstanceId)); postMethod.addRequestHeader("Authorization", "Basic " + appToken); postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded"); httpClient.executeMethod(postMethod); response = postMethod.getResponseBodyAsString(); log.info(response); JSONObject jsonObject = new JSONObject(response); AccessTokenInfo accessTokenInfo = new AccessTokenInfo(); accessTokenInfo.setAccess_token(jsonObject.getString("access_token")); accessTokenInfo.setRefresh_token(jsonObject.getString("refresh_token")); accessTokenInfo.setExpires_in(jsonObject.getInt("expires_in")); accessTokenInfo.setToken_type(jsonObject.getString("token_type")); return accessTokenInfo; } catch (NoSuchAlgorithmException | KeyManagementException | IOException | JSONException e) { log.error(e.getMessage()); throw new AccessTokenException("Configuration Error for Access Token Generation"); } catch (NullPointerException e) { return null; } }
From source file:org.xmlblackbox.test.infrastructure.xml.HTTPUploader.java
public void uploadFile(MemoryData memory, HTTPUploader httpClient) throws TestException, HttpException, IOException { int ris;/*from w w w . ja va2 s. co m*/ HttpClient hClient = new HttpClient(); Properties prop = memory.getOrCreateRepository(getRepositoryName()); logger.info("prop " + prop); /** * Effettua la login */ String usernameStr = (String) httpClient.getParameters().get("username"); String passwordStr = (String) httpClient.getParameters().get("password"); Properties fileProperties = memory.getOrCreateRepository(Repository.FILE_PROPERTIES); logger.info("Login al " + urlLogin); PostMethod postMethodLogin = new PostMethod(urlLogin); NameValuePair username = new NameValuePair(); username.setName("userId"); username.setValue(usernameStr); logger.info("username " + usernameStr); NameValuePair password = new NameValuePair(); password.setName("password"); password.setValue(passwordStr); logger.info("password " + passwordStr); if (usernameStr != null) { postMethodLogin.addParameter(username); } if (passwordStr != null) { postMethodLogin.addParameter(password); } ris = hClient.executeMethod(postMethodLogin); logger.debug("ris Login password " + passwordStr + " " + ris); if (ris != HttpStatus.SC_MOVED_TEMPORARILY) { throw new TestException("Error during login for uploading the file"); } XmlObject[] domandeXml = null; File fileXML = new File(httpClient.getFileToUpload()); PostMethod postm = new PostMethod(urlUpload); logger.debug("fileXML.getName() " + fileXML.getName()); logger.debug("fileXML " + fileXML); logger.debug("postm.getParams() " + postm.getParams()); logger.debug("httpClient.getParameters().get(\"OPERATION_UPLOAD_NAME\") " + httpClient.getParameters().get("OPERATION_UPLOAD_NAME")); logger.debug("httpClient.getParameters().get(\"OPERATION_UPLOAD_VALUE\") " + httpClient.getParameters().get("OPERATION_UPLOAD_VALUE")); try { Part[] parts = { new StringPart(httpClient.getParameters().get("OPERATION_UPLOAD_NAME"), httpClient.getParameters().get("OPERATION_UPLOAD_VALUE")), new FilePart("file", fileXML.getName(), fileXML) }; postm.setRequestEntity(new MultipartRequestEntity(parts, postm.getParams())); logger.debug("parts " + parts); } catch (FileNotFoundException e2) { logger.error("FileNotFoundException ", e2); throw new TestException(e2, "FileNotFoundException "); } hClient.getHttpConnectionManager().getParams().setConnectionTimeout(8000); try { ris = hClient.executeMethod(postm); logger.info("ris Upload password " + passwordStr + " " + ris); logger.debug("ris Upload password " + passwordStr + " " + ris); if (ris == HttpStatus.SC_OK) { //logger.info("Upload completo, risposta=" + postm.getResponseBodyAsString()); InputStream in = postm.getResponseBodyAsStream(); //OutputStream out = new FileOutputStream(new File(prop.getProperty("FILE_RISPOSTA_SERVLET"))); OutputStream out = new FileOutputStream(new File(httpClient.getFileOutput())); OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8"); InputStreamReader reader = new InputStreamReader(in, "UTF-8"); BufferedReader bufferedReader = new BufferedReader(reader); // Transfer bytes from in to out //byte[] buf = new byte[1024]; //int len; String linea = null; while ((linea = bufferedReader.readLine()) != null) { writer.write(linea); } writer.close(); reader.close(); in.close(); out.close(); } else { logger.error("Upload failed, response =" + HttpStatus.getStatusText(ris)); logger.error("Exception : Server response not correct "); throw new TestException("Exception : Server response not correct "); } } catch (HttpException e) { logger.error("Exception : Server response not correct ", e); throw new TestException(e, ""); } catch (IOException e) { logger.error("Exception : Server response not correct ", e); throw new TestException(e, ""); } finally { postm.releaseConnection(); } }
From source file:pl.nask.hsn2.connector.CuckooRESTConnector.java
public final long sendURL(String urlForProc, Set<NameValuePair> cuckooParams) throws CuckooException { PostMethod post = new PostMethod(cuckooURL + SEND_URL_TASK); post.addParameter(new NameValuePair("url", urlForProc)); for (NameValuePair pair : cuckooParams) { post.addParameter(pair);/*from www . jav a 2s. c o m*/ } return sendPost(post); }
From source file:rotmg.net.AvailableServers.java
/** * We are required to provide this post data with this request, otherwise * the request will fail. With too many failures, this method will * begin to return "<Error>LoginError.tooManyFails</Error>" * //from w ww .j a v a 2 s . co m * game_net rotmg * ignore 9858 * game_net_user_id * do_login true * play_platform rotmg * guid <guid> * password * @return */ private static PostMethod makePost() { PostMethod post = new PostMethod("https://realmofthemadgod.appspot.com/char/list"); post.addParameter(new NameValuePair("game_net", "rotmg")); post.addParameter(new NameValuePair("ignore", "9193")); post.addParameter(new NameValuePair("game_net_user_id", "")); post.addParameter(new NameValuePair("do_login", "true")); post.addParameter(new NameValuePair("play_platform", "rotmg")); if (UserConfig.GUEST_GUID != null) { post.addParameter(new NameValuePair("guid", UserConfig.GUEST_GUID)); } post.addParameter(new NameValuePair("password", "")); return post; }
From source file:ucar.unidata.ui.HttpFormEntry.java
private static PostMethod getMethod(List entries, String urlPath) { PostMethod postMethod = new PostMethod(urlPath); boolean anyFiles = false; int count = 0; List goodEntries = new ArrayList(); for (int i = 0; i < entries.size(); i++) { HttpFormEntry formEntry = (HttpFormEntry) entries.get(i); if (!formEntry.okToPost()) { continue; }/*from ww w . j a v a 2 s.c o m*/ goodEntries.add(entries.get(i)); if (formEntry.type == TYPE_FILE) { anyFiles = true; } } if (anyFiles) { Part[] parts = new Part[goodEntries.size()]; for (int i = 0; i < goodEntries.size(); i++) { HttpFormEntry formEntry = (HttpFormEntry) goodEntries.get(i); if (formEntry.type == TYPE_FILE) { parts[i] = formEntry.getFilePart(); } else { //Not sure why but we have seen a couple of times //the byte value '0' gets into one of these strings //This causes an error in the StringPart. // System.err.println(" String value = formEntry.getValue(); char with = new String(" ").charAt(0); while (value.indexOf(0) >= 0) { value = value.replace((char) 0, with); } parts[i] = new StringPart(formEntry.getName(), value); } } postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams())); } else { for (int i = 0; i < goodEntries.size(); i++) { HttpFormEntry formEntry = (HttpFormEntry) goodEntries.get(i); postMethod.addParameter(new NameValuePair(formEntry.getName(), formEntry.getValue())); } } return postMethod; }