List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestBody
public void setRequestBody(NameValuePair[] paramArrayOfNameValuePair) throws IllegalArgumentException
From source file:org.bibsonomy.recommender.tags.WebserviceTagRecommender.java
@Override public void addRecommendedTags(final Collection<RecommendedTag> recommendedTags, final Post<? extends Resource> post) { // render post // FIXME: choose buffer size final StringWriter sw = new StringWriter(100); renderPost(post, sw);/* ww w . j a v a 2s . c o m*/ // Create a method instance. final NameValuePair[] data = { new NameValuePair(ID_RECQUERY, sw.toString()), new NameValuePair(ID_POSTID, "" + post.getContentId()) }; // Create a method instance. // send request // FIXME: THIS IS JUST FOR DOWNWARD COMPATIBILITY DURING THE DC09 RECOMMENDER CHALLENGE // Replace the following three lines of code with: // InputStreamReader input = sendRequest(data, "/"+METHOD_GETRECOMMENDEDTAGS); PostMethod cnct = new PostMethod(getAddress().toString()); cnct.setRequestBody(data); InputStreamReader input = sendRequest(cnct); if (input == null) { cnct.releaseConnection(); cnct = new PostMethod(getAddress().toString() + "/" + METHOD_GETRECOMMENDEDTAGS); cnct.setRequestBody(data); input = sendRequest(cnct); } // Deal with the response. SortedSet<RecommendedTag> result = null; if (input != null) { try { result = renderer.parseRecommendedTagList(input); } catch (final Exception e) { log.error("Error parsing recommender response (" + getAddress().toString() + ").", e); result = null; } } if (result != null) recommendedTags.addAll(result); cnct.releaseConnection(); }
From source file:org.bibsonomy.recommender.tags.WebserviceTagRecommender.java
@Override public void setFeedback(final Post<? extends Resource> post) { // render post // FIXME: choose buffer size final StringWriter sw = new StringWriter(100); renderPost(post, sw);/*from w ww . j a v a2 s .c om*/ // Create a method instance. final NameValuePair[] data = { new NameValuePair(ID_FEEDBACK, sw.toString()), new NameValuePair(ID_RECQUERY, sw.toString()), // for downward compatibility new NameValuePair(ID_POSTID, "" + post.getContentId()) }; // send request final PostMethod cnct = new PostMethod(getAddress().toString() + "/" + METHOD_SETFEEDBACK); cnct.setRequestBody(data); final InputStreamReader input = sendRequest(cnct); // Deal with the response. if (input != null) { final String status = renderer.parseStat(input); log.info("Feedback status: " + status); } cnct.releaseConnection(); }
From source file:org.biomart.martservice.MartServiceUtils.java
/** * Sends a query to the Biomart webservice and constructs an array of List * of String results from the tab separated rows of data returned by the * webservice./* w w w. j a v a2 s. c om*/ * * @param martServiceLocation * the URL of the Biomart webservice * @param query * the query to send to the webservice * @return an array of List of String * @throws MartServiceException * if the Biomart webservice returns an error or is unavailable */ public static Object[] getResults(String martServiceLocation, String requestId, Query query) throws MartServiceException { Object[] results = new Object[0]; // int attributes = query.getAttributes().size(); int attributes = getAttributeCount(query.getAttributes()); boolean count = query.getCount() == 1; // if there are no attributes and we're not doing a count there's no // point in doing the query if (attributes > 0 || count) { // The 'new' 0.5 server now resolves the attribute lists so there's // no need to do the split here any more // String queryXml = queryToXML(splitAttributeLists(query)); String queryXml = queryToXML(query); logger.info(queryXml); NameValuePair[] data = { new NameValuePair(QUERY_ATTRIBUTE, queryXml) }; PostMethod method = new PostMethod(martServiceLocation); method.setRequestBody(data); try { InputStream in = executeMethod(method, martServiceLocation); if (query.getFormatter() == null) { results = tabSeparatedReaderToResults(new InputStreamReader(in), count ? 1 : attributes); if (!count) { results = reassembleAttributeLists(results, query); } } else { results = readResult(in, query.getFormatter()); } in.close(); } catch (IOException e) { String errorMessage = "Error reading data from " + martServiceLocation; throw new MartServiceException(errorMessage, e); } finally { method.releaseConnection(); } } return results; }
From source file:org.biomart.martservice.MartServiceUtils.java
public static void putResults(String martServiceLocation, String requestId, Query query, ResultReceiver resultReceiver) throws MartServiceException, ResultReceiverException { int attributeCount = getAttributeCount(query.getAttributes()); boolean count = query.getCount() == 1; // if there are no attributes and we're not doing a count there's no // point in doing the query if (attributeCount > 0 || count) { String queryXml = queryToXML(query); logger.info(queryXml);// w w w. j av a 2 s .c om NameValuePair[] data = { new NameValuePair(QUERY_ATTRIBUTE, queryXml) }; PostMethod method = new PostMethod(martServiceLocation); method.setRequestBody(data); try { InputStream in = executeMethod(method, martServiceLocation); if (query.getFormatter() == null) { if (count) { resultReceiver.receiveResult(tabSeparatedReaderToResults(new InputStreamReader(in), 1), 0); } else { List<Attribute> attributes = query.getAttributes(); Object[] result = new Object[attributes.size()]; BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in)); String line = bufferedReader.readLine(); for (long i = 0; line != null; line = bufferedReader.readLine(), i++) { String[] tokens = line.split("\t", -1); if (attributeCount == tokens.length) { for (int ri = 0, ti = 0; ri < result.length && ti < tokens.length; ri++) { Attribute attribute = attributes.get(ri); if (attribute.getAttributes() == null) { result[ri] = tokens[ti]; ti++; } else { int nestedAttributeCount = attribute.getAttributesCount(); List<Object> list = new ArrayList<Object>(); for (int j = 0; j < nestedAttributeCount; j++) { list.add(tokens[ti]); ti++; } result[ri] = list; } } resultReceiver.receiveResult(result, i); } else { resultReceiver.receiveError(line, i); } } } } else { resultReceiver.receiveResult(readResult(in, query.getFormatter()), 0); } in.close(); } catch (IOException e) { String errorMessage = "Error reading data from " + martServiceLocation; throw new MartServiceException(errorMessage, e); } finally { method.releaseConnection(); } } }
From source file:org.bpmscript.http.HttpClientRestService.java
/** * @throws BpmScriptException /*from www. j a va 2 s .c om*/ * @see org.bpmscript.http.IRestService#post(java.lang.String, java.lang.String) */ @SuppressWarnings("deprecation") public String post(String url, String content) throws BpmScriptException { HttpClient client = new HttpClient(); PostMethod postMethod = new PostMethod(url); postMethod.setRequestBody(content); try { int status = client.executeMethod(postMethod); if (status == 200) { String result = StreamService.DEFAULT_INSTANCE.readFully(postMethod.getResponseBodyAsStream()); return result; } else { throw new BpmScriptException("Error status of " + status); } } catch (HttpException e) { throw new BpmScriptException(e); } catch (IOException e) { throw new BpmScriptException(e); } finally { postMethod.releaseConnection(); } }
From source file:org.broadleafcommerce.payment.service.gateway.AbstractPayPalExpressService.java
@Override public PayPalResponse communicateWithVendor(PayPalRequest paymentRequest) throws Exception { HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(getServerUrl()); List<NameValuePair> nvps = requestGenerator.buildRequest(paymentRequest); postMethod.setRequestBody(nvps.toArray(new NameValuePair[nvps.size()])); httpClient.executeMethod(postMethod); String responseString = postMethod.getResponseBodyAsString(); return responseGenerator.buildResponse(responseString, paymentRequest); }
From source file:org.broadleafcommerce.vendor.paypal.service.payment.PayPalPaymentServiceImpl.java
protected String communicateWithVendor(PayPalRequest paymentRequest) throws IOException { HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(getServerUrl()); List<NameValuePair> nvps = requestGenerator.buildRequest(paymentRequest); postMethod.setRequestBody(nvps.toArray(new NameValuePair[nvps.size()])); httpClient.executeMethod(postMethod); return postMethod.getResponseBodyAsString(); }
From source file:org.cauldron.tasks.HttpCall.java
/** * Running an HttpTask retrieves the path contents according to the task * attributes. POST body comes from the input. *//*from w ww. jav a 2 s .c om*/ public Object run(Context context, Object input) throws TaskException { // For POST, body must be available as input. String body = null; if (!isGet) { body = (String) context.convert(input, String.class); if (body == null) throw new TaskException("HTTP POST input must be convertible to String"); } // Prepare request parameters. NameValuePair[] nvp = null; if (params != null && params.size() > 0) { nvp = new NameValuePair[params.size()]; int count = 0; for (Iterator entries = params.entrySet().iterator(); entries.hasNext();) { Map.Entry entry = (Map.Entry) entries.next(); String key = (String) entry.getKey(); String value = (String) entry.getValue(); nvp[count++] = new NameValuePair(key, value); } } // Create the retrieval method and set parameters. // HttpMethod method; if (isGet) { GetMethod get = new GetMethod(); if (nvp != null) get.setQueryString(nvp); method = get; } else { PostMethod post = new PostMethod(); post.setRequestBody(body); if (nvp != null) post.addParameters(nvp); method = post; } // Make the call. method.setPath(path); HttpConnection connection = connectionManager.getConnection(config); try { connection.open(); method.execute(new HttpState(), connection); return method.getResponseBodyAsString(); } catch (HttpException e) { throw new TaskException(e); } catch (IOException e) { throw new TaskException(e); } finally { connection.close(); } }
From source file:org.conqat.engine.bugzilla.lib.BugzillaWebClient.java
/** * Authenticate with Bugzilla server. Note that Bugzilla servers can often * be accessed without credentials in a read-only manner. Hence, credentials * are not necessarily required although your Bugzilla server requires them * to edit bugs. Depending on the permissions set on the Bugzilla server, * calls to {@link #query(Set, Set, Set)} may return different results * whether you are authenticated or not. * //from ww w. j a va 2s . c o m * @throws BugzillaException * If Bugzilla server responded with an error. * @throws IOException * if an I/O problem occurs while obtaining the response from * Bugzilla * @throws HttpException * if a protocol exception occurs */ public void authenticate(String username, String password) throws BugzillaException, HttpException, IOException { NameValuePair[] formData = new NameValuePair[2]; formData[0] = new NameValuePair("Bugzilla_login", username); formData[1] = new NameValuePair("Bugzilla_password", password); PostMethod postMethod = new PostMethod(server + "/index.cgi"); postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); postMethod.setRequestBody(formData); postMethod.setDoAuthentication(true); postMethod.setFollowRedirects(false); client.getState().clearCookies(); try { int code = client.executeMethod(postMethod); if (code != HttpStatus.SC_OK) { throw new BugzillaException("Authentication failed: " + HttpStatus.getStatusText(code)); } // Bugzilla assigns cookies if everything went ok. Cookie[] cookies = client.getState().getCookies(); if (cookies.length == 0) { throw new BugzillaException("Authentication failed!"); } // the following loop fixes CR#2801. For some reason, Bugzilla only // accepts the cookies if they are not limited to secure // connections. for (Cookie c : cookies) { c.setSecure(false); } } finally { postMethod.releaseConnection(); } }
From source file:org.conqat.engine.bugzilla.lib.BugzillaWebClient.java
/** * This executes an HTTP post on a Bugzilla URL and deals with the handling * of error messages./* ww w .j av a 2 s. c o m*/ * * @return the body of the HTTP response. * @throws BugzillaException * If Bugzilla server responded with an error. * @throws IOException * if an I/O problem occurs while obtaining the response from * Bugzilla * @throws HttpException * if a protocol exception occurs */ private String executePostMethod(String url, BugzillaFields fields) throws HttpException, IOException, BugzillaException { PostMethod postMethod = new PostMethod(server + "/" + url); postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); postMethod.setRequestBody(fields.createFormData()); postMethod.setFollowRedirects(false); try { int result = client.executeMethod(postMethod); if (result != HttpStatus.SC_OK) { throw new BugzillaException("Error occured when adding comment."); } String response = postMethod.getResponseBodyAsString(); if (StringUtils.containsOneOf(response, ERROR_MARKERS)) { throw new BugzillaException(extractErrorMessage(response)); } return response; } finally { postMethod.releaseConnection(); } }