List of usage examples for org.apache.commons.httpclient.methods PostMethod addParameters
public void addParameters(NameValuePair[] paramArrayOfNameValuePair)
From source file:com.legendshop.central.license.HttpClientLicenseHelper.java
public String postMethod(String paramString) { String str = null;/*from w w w. j ava 2s .c o m*/ HttpClient localHttpClient = new HttpClient(); PostMethod localPostMethod = new PostMethod(this._$1); NameValuePair[] arrayOfNameValuePair = new NameValuePair[1]; arrayOfNameValuePair[0] = new NameValuePair("_ENTITY", paramString); localPostMethod.addParameters(arrayOfNameValuePair); try { localHttpClient.executeMethod(localPostMethod); str = localPostMethod.getResponseBodyAsString(); } catch (Exception localException) { } finally { localPostMethod.releaseConnection(); } return str; }
From source file:edu.ucsb.eucalyptus.admin.server.extensions.store.ImageStoreServiceImpl.java
public String requestJSON(String sessionId, Method method, String uri, Parameter[] params) { UserInfoWeb user;//from www.ja v a 2 s . co m try { user = EucalyptusWebBackendImpl.getUserRecord(sessionId); } catch (Exception e) { return errorJSON("Session authentication error: " + e.getMessage()); } NameValuePair[] finalParams; try { finalParams = getFinalParameters(method, uri, params, user); } catch (MalformedURLException e) { return errorJSON("Malformed URL: " + uri); } HttpClient client = new HttpClient(); HttpMethod httpMethod; if (method == Method.GET) { GetMethod getMethod = new GetMethod(uri); httpMethod = getMethod; getMethod.setQueryString(finalParams); } else if (method == Method.POST) { PostMethod postMethod = new PostMethod(uri); httpMethod = postMethod; postMethod.addParameters(finalParams); } else { throw new UnsupportedOperationException("Unknown method"); } try { int statusCode = client.executeMethod(httpMethod); String str = ""; InputStream in = httpMethod.getResponseBodyAsStream(); byte[] readBytes = new byte[1024]; int bytesRead = -1; while ((bytesRead = in.read(readBytes)) > 0) { str += new String(readBytes, 0, bytesRead); } return str; } catch (HttpException e) { return errorJSON("Protocol error: " + e.getMessage()); } catch (IOException e) { return errorJSON("Proxy error: " + e.getMessage()); } finally { httpMethod.releaseConnection(); } }
From source file:edu.ku.brc.services.biogeomancer.BioGeomancer.java
/** * Sends a georeferencing request to the BioGeomancer web service. * //from w ww.j a v a 2 s .c om * @param id id * @param country country * @param adm1 country * @param adm2 adm2 * @param localityArg locality * @return returns the response body content (as XML) * @throws IOException a network error occurred while contacting the BioGeomancer service */ public static String getBioGeomancerResponse(final String id, final String country, final String adm1, final String adm2, final String localityArg) throws IOException { HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod("http://130.132.27.130/cgi-bin/bgm-0.2/batch_test.pl"); //$NON-NLS-1$ StringBuilder strBuf = new StringBuilder(128); strBuf.append("\"" + id + "\","); //$NON-NLS-1$ //$NON-NLS-2$ strBuf.append("\"" + country + "\","); //$NON-NLS-1$ //$NON-NLS-2$ strBuf.append("\"" + adm1 + "\","); //$NON-NLS-1$ //$NON-NLS-2$ strBuf.append("\"" + (adm2 != null ? adm2 : "") + "\","); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ strBuf.append("\"" + localityArg + "\"\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ NameValuePair[] postData = { //new NameValuePair("batchtext", "\"12931\",\"Mexico\",\"Veracruz\",\"\",\"12 km NW of Catemaco\"\r\n"), new NameValuePair("batchtext", strBuf.toString()), //$NON-NLS-1$ new NameValuePair("format", "xml") }; //$NON-NLS-1$ //$NON-NLS-2$ // the 2.0 beta1 version has a // PostMethod.setRequestBody(NameValuePair[]) // method, as addParameters is deprecated postMethod.addParameters(postData); httpClient.executeMethod(postMethod); InputStream iStream = postMethod.getResponseBodyAsStream(); StringBuilder sb = new StringBuilder(); byte[] bytes = new byte[8196]; int numBytes = 0; do { numBytes = iStream.read(bytes); if (numBytes > 0) { sb.append(new String(bytes, 0, numBytes)); } } while (numBytes > 0); //release the connection used by the method postMethod.releaseConnection(); return sb.toString(); }
From source file:com.shelrick.openamplify.client.OpenAmplifyClientImpl.java
@Override public OpenAmplifyResponse searchText(String inputText, Analysis analysis, List<String> searchTermsList, Integer maxTopicResults) throws OpenAmplifyClientException { List<NameValuePair> params = getBaseParams(); params.add(new NameValuePair("inputtext", inputText)); params.add(new NameValuePair("analysis", analysis.type())); params.add(new NameValuePair("searchTerms", getSearchTerms(searchTermsList))); params.add(new NameValuePair("maxtopicresult", maxTopicResults.toString())); PostMethod postMethod = new PostMethod(apiUrl); postMethod.addParameters(params.toArray(new NameValuePair[1])); String responseText = doRequest(postMethod); return parseResponse(responseText, analysis); }
From source file:com.shelrick.openamplify.client.OpenAmplifyClientImpl.java
@Override public OpenAmplifyResponse analyzeText(String inputText, Analysis analysis, Integer maxTopicResults) throws OpenAmplifyClientException { List<NameValuePair> params = getBaseParams(); inputText = inputText.replaceAll("'@[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]@'", " "); params.add(new NameValuePair("inputtext", inputText)); params.add(new NameValuePair("analysis", analysis.type())); params.add(new NameValuePair("maxtopicresult", maxTopicResults.toString())); PostMethod postMethod = new PostMethod(apiUrl); postMethod.addParameters(params.toArray(new NameValuePair[1])); String responseText = doRequest(postMethod); //System.out.println(responseText); return parseResponse(responseText, analysis); }
From source file:ClientPost.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod("http://localhost:8080/home/viewPost.jsp"); NameValuePair[] postData = { new NameValuePair("username", "devgal"), new NameValuePair("department", "development"), new NameValuePair("email", "devgal@yahoo.com") }; //the 2.0 beta1 version has a // PostMethod.setRequestBody(NameValuePair[]) //method, as addParameters is deprecated postMethod.addParameters(postData); httpClient.executeMethod(postMethod); //display the response to the POST method response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); //A "200 OK" HTTP Status Code if (postMethod.getStatusCode() == HttpStatus.SC_OK) { out.println(postMethod.getResponseBodyAsString()); } else {/*from ww w . j a v a 2 s . c o m*/ out.println("The POST action raised an error: " + postMethod.getStatusLine()); } //release the connection used by the method postMethod.releaseConnection(); }
From source file:de.laeubisoft.tools.ant.validation.W3CMarkupValidationTask.java
/** * Creates the actual request to the validation server for a given * {@link URL} and returns an inputstream the result can be read from * /*from w ww . j av a 2 s . co m*/ * @param uriToCheck * the URL to check * @return the stream to read the response from * @throws IOException * if unrecoverable communication error occurs * @throws BuildException * if server returned unexspected results */ private InputStream buildConnection(final URL uriToCheck) throws IOException, BuildException { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new NameValuePair("output", VALIDATOR_FORMAT_OUTPUT)); if (uriToCheck != null) { params.add(new NameValuePair("uri", uriToCheck.toString())); } else { if (fragment != null) { params.add(new NameValuePair("fragment", fragment)); } } if (debug) { params.add(new NameValuePair("debug", "1")); } if (charset != null) { params.add(new NameValuePair("charset", charset)); } if (doctype != null) { params.add(new NameValuePair("doctype", doctype)); } HttpClient httpClient = new HttpClient(); HttpMethodBase method; if (uriToCheck != null) { //URIs must be checked wia traditonal GET... GetMethod getMethod = new GetMethod(validator); getMethod.setQueryString(params.toArray(new NameValuePair[0])); method = getMethod; } else { PostMethod postMethod = new PostMethod(validator); if (fragment != null) { //Fragment request can be checked via FORM Submission postMethod.addParameters(params.toArray(new NameValuePair[0])); } else { //Finally files must be checked with multipart-forms.... postMethod.setRequestEntity(Tools.createFileUpload(uploaded_file, "uploaded_file", charset, params, postMethod.getParams())); } method = postMethod; } int result = httpClient.executeMethod(method); if (result == HttpStatus.SC_OK) { return method.getResponseBodyAsStream(); } else { throw new BuildException("Server returned " + result + " " + method.getStatusText()); } }
From source file:com.redhat.topicindex.security.FedoraAccountSystem.java
@SuppressWarnings("unchecked") private boolean authenticate() throws LoginException { if (password == null || username == null) throw new LoginException("No Username/Password found"); if (password.equals("") || username.equals("")) throw new LoginException("No Username/Password found"); HttpClient client = new HttpClient(); PostMethod method = new PostMethod(FEDORA_JSON_URL); try {//from w ww . j a v a 2s .c o m // Generate the data to send List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new NameValuePair("username", username)); formparams.add(new NameValuePair("user_name", username)); formparams.add(new NameValuePair("password", String.valueOf(password))); formparams.add(new NameValuePair("login", "Login")); method.addParameters(formparams.toArray(new NameValuePair[formparams.size()])); // Send the data and get the response client.executeMethod(method); // Handle the response BufferedReader br = new BufferedReader( new InputStreamReader(new ByteArrayInputStream(method.getResponseBody()))); JSONParser parser = new JSONParser(); ContainerFactory containerFactory = new ContainerFactory() { public List creatArrayContainer() { return new LinkedList(); } public Map createObjectContainer() { return new LinkedHashMap(); } }; // Parse the response to check authentication success and valid groups String line; while ((line = br.readLine()) != null) { Map json = (Map) parser.parse(line, containerFactory); if (json.containsKey("success") && json.containsKey("person")) { if (json.get("person") instanceof LinkedHashMap) { LinkedHashMap person = (LinkedHashMap) json.get("person"); if (person.get("status").equals("active")) { if (person.containsKey("approved_memberships")) { if (person.get("approved_memberships") instanceof LinkedList) { if (!checkCLAAgreement(((LinkedList) person.get("approved_memberships")))) { throw new LoginException("FAS authentication failed for " + username + ". Contributor License Agreement not yet signed"); } } else if (person.get("approved_memberships") instanceof LinkedHashMap) { if (!checkCLAAgreement(((LinkedHashMap) person.get("approved_memberships")))) { throw new LoginException("FAS authentication failed for " + username + ". Contributor License Agreement not yet signed"); } } } else { throw new LoginException("FAS authentication failed for " + username + ". Contributor License Agreement not yet signed"); } } else { throw new LoginException( "FAS authentication failed for " + username + ". Account is not active"); } } } else { throw new LoginException("Error: FAS authentication failed for " + username); } } } catch (LoginException e) { throw e; } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); } finally { method.releaseConnection(); } return true; }
From source file:com.zenkey.net.prowser.Tab.java
/************************************************************************** * Adds form data to a POST method object. * //from www. ja v a 2s . c o m * @param request The request object. * @param postMethod The POST method object. */ private static void addPostParameters(Request request, PostMethod postMethod) { // Convert the request's parameter map to an array of name-value pairs Map<String, String[]> parameterMap = request.getParameterMap(); ArrayList<NameValuePair> parameterList = new ArrayList<NameValuePair>(); for (String name : parameterMap.keySet()) { String[] values = request.getParameterValues(name); for (String value : values) { parameterList.add(new NameValuePair(name, value)); } } NameValuePair[] parameterPairs = parameterList.toArray(new NameValuePair[parameterList.size()]); // Add the parameters to the POST method postMethod.addParameters(parameterPairs); }
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"); }/*www . j a va 2 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()])); }