List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestBody
public void setRequestBody(NameValuePair[] paramArrayOfNameValuePair) throws IllegalArgumentException
From source file:org.openhab.action.telegram.internal.Telegram.java
@ActionDoc(text = "Sends a Telegram via Telegram REST API - direct message") static public boolean sendTelegram(@ParamDoc(name = "group") String group, @ParamDoc(name = "message") String message) { if (groupTokens.get(group) == null) { logger.error("Bot '{}' not defined, action skipped", group); return false; }//from w ww .j a v a 2 s . c om String url = String.format(TELEGRAM_URL, groupTokens.get(group).getToken()); HttpClient client = new HttpClient(); PostMethod postMethod = new PostMethod(url); postMethod.getParams().setSoTimeout(HTTP_TIMEOUT); postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); NameValuePair[] data = { new NameValuePair("chat_id", groupTokens.get(group).getChatId()), new NameValuePair("text", message) }; postMethod.setRequestBody(data); try { int statusCode = client.executeMethod(postMethod); if (statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) { return true; } if (statusCode != HttpStatus.SC_OK) { logger.warn("Method failed: {}", postMethod.getStatusLine()); return false; } InputStream tmpResponseStream = postMethod.getResponseBodyAsStream(); Header encodingHeader = postMethod.getResponseHeader("Content-Encoding"); if (encodingHeader != null) { for (HeaderElement ehElem : encodingHeader.getElements()) { if (ehElem.toString().matches(".*gzip.*")) { tmpResponseStream = new GZIPInputStream(tmpResponseStream); logger.debug("GZipped InputStream from {}", url); } else if (ehElem.toString().matches(".*deflate.*")) { tmpResponseStream = new InflaterInputStream(tmpResponseStream); logger.debug("Deflated InputStream from {}", url); } } } String responseBody = IOUtils.toString(tmpResponseStream); if (!responseBody.isEmpty()) { logger.debug(responseBody); } } catch (HttpException e) { logger.error("Fatal protocol violation: {}", e.toString()); } catch (IOException e) { logger.error("Fatal transport error: {}", e.toString()); } finally { postMethod.releaseConnection(); } return true; }
From source file:org.openhab.binding.squeezebox.internal.utils.HttpUtils.java
/** * Simple logic to perform a post request * //from w ww. j av a 2 s .c o m * @param url * @param timeout * @return */ public static String post(String url, String postData) throws Exception { PostMethod method = new PostMethod(url); method.setRequestBody(postData); method.getParams().setSoTimeout(TIMEOUT); try { int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.error("Method failed: {}", method.getStatusLine()); throw new Exception("Method failed: " + method.getStatusLine()); } byte[] responseBody = method.getResponseBody(); return new String(responseBody); } finally { method.releaseConnection(); } }
From source file:org.openo.auth.rest.client.ClientCommunicationUtil.java
/** * API for connecting the client and providing the result for the requested api service. * Especially for the PATCH Request, as in JAVA 7, <tt> HTTPURLConnection </tt> does not * support PATCH, the supported methods were : * GET,POST,HEAD,OPTIONS,PUT,DELETE,TRACE * <br/>//from w ww . ja v a2 s . com * * @param url * @param authToken * @param body * @return * @throws HttpException * @throws IOException * @since SDNO 0.5 */ private Response getResponseFromPatchService(String url, String authToken, String body) throws HttpException, IOException { PostMethod method = new PostMethod(url) { @Override public String getName() { return Constant.TYPE_PATCH; } }; method.setRequestHeader(Constant.TOKEN_AUTH, authToken); method.setRequestHeader(HttpHeaders.CONTENT_TYPE, Constant.MEDIA_TYPE_JSON); method.setRequestBody(body); HttpClient client = new HttpClient(); LOGGER.info("Current URI For HTTP Client -> " + method.getURI()); client.executeMethod(method); LOGGER.info("Status Code -> " + method.getStatusCode() + " Response body -> " + method.getResponseBodyAsString()); return Response.status(method.getStatusCode()).header(Constant.TOKEN_SUBJECT, authToken) .entity(method.getResponseBodyAsStream()).build(); }
From source file:org.openrdf.http.client.HTTPClient.java
protected HttpMethod getQueryMethod(QueryLanguage ql, String query, String baseURI, Dataset dataset, boolean includeInferred, int maxQueryTime, Binding... bindings) { PostMethod method = new PostMethod(getRepositoryURL()); setDoAuthentication(method);//from w w w . j av a 2 s . co m method.setRequestHeader("Content-Type", Protocol.FORM_MIME_TYPE + "; charset=utf-8"); List<NameValuePair> queryParams = getQueryMethodParameters(ql, query, baseURI, dataset, includeInferred, maxQueryTime, bindings); method.setRequestBody(queryParams.toArray(new NameValuePair[queryParams.size()])); return method; }
From source file:org.openrdf.http.client.HTTPClient.java
protected HttpMethod getUpdateMethod(QueryLanguage ql, String update, String baseURI, Dataset dataset, boolean includeInferred, Binding... bindings) { PostMethod method = new PostMethod(Protocol.getStatementsLocation(getRepositoryURL())); setDoAuthentication(method);//ww w .jav a2 s . com method.setRequestHeader("Content-Type", Protocol.FORM_MIME_TYPE + "; charset=utf-8"); List<NameValuePair> queryParams = getUpdateMethodParameters(ql, update, baseURI, dataset, includeInferred, bindings); method.setRequestBody(queryParams.toArray(new NameValuePair[queryParams.size()])); return method; }
From source file:org.paxml.bean.HttpTag.java
private PostMethod setPostBody(PostMethod post) { Map<String, List<String>> value = getNameValuePairs(body, "body"); if (value != null) { for (Map.Entry<String, List<String>> entry : value.entrySet()) { for (String v : entry.getValue()) { post.addParameter(entry.getKey(), v); }/*from ww w . j a v a 2s . c om*/ } } else if (body != null) { post.setRequestBody(body.toString()); } return post; }
From source file:org.paxml.bean.SoapTag.java
/** * {@inheritDoc}//from w w w. ja va 2 s . c o m */ @Override protected Object doInvoke(Context context) throws Exception { HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); ByteArrayOutputStream out = new ByteArrayOutputStream(); write(out); // method.setRequestHeader(headerName, headerValue); method.setRequestBody(out.toString("UTF-8")); method.setRequestHeader("Content-Type", "text/xml;charset=UTF-8"); if (headers != null) { Map<?, ?> hd = (Map<?, ?>) this.headers; for (Map.Entry<?, ?> entry : hd.entrySet()) { Object obj = entry.getValue(); if (obj != null) { method.setRequestHeader(entry.getKey().toString(), obj.toString()); } } } // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(RETRY, false)); // method.setr try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new PaxmlRuntimeException("Http post failed: " + method.getStatusLine()); } // Read the response body. byte[] responseBody = method.getResponseBody(); // Deal with the response. // Use caution: ensure correct character encoding and is not binary // data return read(new ByteArrayInputStream(responseBody)); } finally { // Release the connection. method.releaseConnection(); } }
From source file:org.pentaho.di.trans.steps.httppost.HTTPPOST.java
private Object[] callHTTPPOST(Object[] rowData) throws KettleException { // get dynamic url ? if (meta.isUrlInField()) { data.realUrl = data.inputRowMeta.getString(rowData, data.indexOfUrlField); }//from ww w . java2 s. c o m FileInputStream fis = null; try { if (isDetailed()) { logDetailed(BaseMessages.getString(PKG, "HTTPPOST.Log.ConnectingToURL", data.realUrl)); } // Prepare HTTP POST // HttpClient HTTPPOSTclient = SlaveConnectionManager.getInstance().createHttpClient(); PostMethod post = new PostMethod(data.realUrl); // post.setFollowRedirects(false); // Set timeout if (data.realConnectionTimeout > -1) { HTTPPOSTclient.getHttpConnectionManager().getParams() .setConnectionTimeout(data.realConnectionTimeout); } if (data.realSocketTimeout > -1) { HTTPPOSTclient.getHttpConnectionManager().getParams().setSoTimeout(data.realSocketTimeout); } if (!Const.isEmpty(data.realHttpLogin)) { HTTPPOSTclient.getParams().setAuthenticationPreemptive(true); Credentials defaultcreds = new UsernamePasswordCredentials(data.realHttpLogin, data.realHttpPassword); HTTPPOSTclient.getState().setCredentials(AuthScope.ANY, defaultcreds); } HostConfiguration hostConfiguration = new HostConfiguration(); if (!Const.isEmpty(data.realProxyHost)) { hostConfiguration.setProxy(data.realProxyHost, data.realProxyPort); } // Specify content type and encoding // If content encoding is not explicitly specified // ISO-8859-1 is assumed by the POSTMethod if (!data.contentTypeHeaderOverwrite) { // can be overwritten now if (Const.isEmpty(data.realEncoding)) { post.setRequestHeader(CONTENT_TYPE, CONTENT_TYPE_TEXT_XML); if (isDebug()) { logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.HeaderValue", CONTENT_TYPE, CONTENT_TYPE_TEXT_XML)); } } else { post.setRequestHeader(CONTENT_TYPE, CONTENT_TYPE_TEXT_XML + "; " + data.realEncoding); if (isDebug()) { logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.HeaderValue", CONTENT_TYPE, CONTENT_TYPE_TEXT_XML + "; " + data.realEncoding)); } } } // HEADER PARAMETERS if (data.useHeaderParameters) { // set header parameters that we want to send for (int i = 0; i < data.header_parameters_nrs.length; i++) { post.addRequestHeader(data.headerParameters[i].getName(), data.inputRowMeta.getString(rowData, data.header_parameters_nrs[i])); if (isDebug()) { logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.HeaderValue", data.headerParameters[i].getName(), data.inputRowMeta.getString(rowData, data.header_parameters_nrs[i]))); } } } // BODY PARAMETERS if (data.useBodyParameters) { // set body parameters that we want to send for (int i = 0; i < data.body_parameters_nrs.length; i++) { data.bodyParameters[i] .setValue(data.inputRowMeta.getString(rowData, data.body_parameters_nrs[i])); if (isDebug()) { logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.BodyValue", data.bodyParameters[i].getName(), data.inputRowMeta.getString(rowData, data.body_parameters_nrs[i]))); } } post.setRequestBody(data.bodyParameters); } // QUERY PARAMETERS if (data.useQueryParameters) { for (int i = 0; i < data.query_parameters_nrs.length; i++) { data.queryParameters[i] .setValue(data.inputRowMeta.getString(rowData, data.query_parameters_nrs[i])); if (isDebug()) { logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.QueryValue", data.queryParameters[i].getName(), data.inputRowMeta.getString(rowData, data.query_parameters_nrs[i]))); } } post.setQueryString(data.queryParameters); } // Set request entity? if (data.indexOfRequestEntity >= 0) { String tmp = data.inputRowMeta.getString(rowData, data.indexOfRequestEntity); // Request content will be retrieved directly // from the input stream // Per default, the request content needs to be buffered // in order to determine its length. // Request body buffering can be avoided when // content length is explicitly specified if (meta.isPostAFile()) { File input = new File(tmp); fis = new FileInputStream(input); post.setRequestEntity(new InputStreamRequestEntity(fis, input.length())); } else { if ((data.realEncoding != null) && (data.realEncoding.length() > 0)) { post.setRequestEntity(new InputStreamRequestEntity( new ByteArrayInputStream(tmp.getBytes(data.realEncoding)), tmp.length())); } else { post.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(tmp.getBytes()), tmp.length())); } } } // Execute request // InputStreamReader inputStreamReader = null; Object[] newRow = null; if (rowData != null) { newRow = rowData.clone(); } try { // used for calculating the responseTime long startTime = System.currentTimeMillis(); // Execute the POST method int statusCode = HTTPPOSTclient.executeMethod(hostConfiguration, post); // calculate the responseTime long responseTime = System.currentTimeMillis() - startTime; if (isDetailed()) { logDetailed( BaseMessages.getString(PKG, "HTTPPOST.Log.ResponseTime", responseTime, data.realUrl)); } // Display status code if (isDebug()) { logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.ResponseCode", String.valueOf(statusCode))); } String body = null; if (statusCode != -1) { if (statusCode == 204) { body = ""; } else { // if the response is not 401: HTTP Authentication required if (statusCode != 401) { // Use request encoding if specified in component to avoid strange response encodings // See PDI-3815 String encoding = data.realEncoding; // Try to determine the encoding from the Content-Type value // if (Const.isEmpty(encoding)) { String contentType = post.getResponseHeader("Content-Type").getValue(); if (contentType != null && contentType.contains("charset")) { encoding = contentType.replaceFirst("^.*;\\s*charset\\s*=\\s*", "") .replace("\"", "").trim(); } } // Get the response, but only specify encoding if we've got one // otherwise the default charset ISO-8859-1 is used by HttpClient if (Const.isEmpty(encoding)) { if (isDebug()) { logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.Encoding", "ISO-8859-1")); } inputStreamReader = new InputStreamReader(post.getResponseBodyAsStream()); } else { if (isDebug()) { logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.Encoding", encoding)); } inputStreamReader = new InputStreamReader(post.getResponseBodyAsStream(), encoding); } StringBuffer bodyBuffer = new StringBuffer(); int c; while ((c = inputStreamReader.read()) != -1) { bodyBuffer.append((char) c); } inputStreamReader.close(); // Display response body = bodyBuffer.toString(); if (isDebug()) { logDebug(BaseMessages.getString(PKG, "HTTPPOST.Log.ResponseBody", body)); } } else { // the status is a 401 throw new KettleStepException( BaseMessages.getString(PKG, "HTTPPOST.Exception.Authentication", data.realUrl)); } } } int returnFieldsOffset = data.inputRowMeta.size(); if (!Const.isEmpty(meta.getFieldName())) { newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, body); returnFieldsOffset++; } if (!Const.isEmpty(meta.getResultCodeFieldName())) { newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, new Long(statusCode)); returnFieldsOffset++; } if (!Const.isEmpty(meta.getResponseTimeFieldName())) { newRow = RowDataUtil.addValueData(newRow, returnFieldsOffset, new Long(responseTime)); } } finally { if (inputStreamReader != null) { inputStreamReader.close(); } // Release current connection to the connection pool once you are done post.releaseConnection(); if (data.realcloseIdleConnectionsTime > -1) { HTTPPOSTclient.getHttpConnectionManager() .closeIdleConnections(data.realcloseIdleConnectionsTime); } } return newRow; } catch (UnknownHostException uhe) { throw new KettleException( BaseMessages.getString(PKG, "HTTPPOST.Error.UnknownHostException", uhe.getMessage())); } catch (Exception e) { throw new KettleException(BaseMessages.getString(PKG, "HTTPPOST.Error.CanNotReadURL", data.realUrl), e); } finally { if (fis != null) { BaseStep.closeQuietly(fis); } } }
From source file:org.proteomecommons.tranche.proxy.UploadThread.java
public void run() { try {/*from www .j a v a 2 s . c o m*/ ServerUtil.waitForStartup(); // set the password of the user zip file uzf.setPassphrase(uzfPassphrase); // register the bouncy castle code Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); aft = new AddFileTool(uzf.getCertificate(), uzf.getPrivateKey()); // should it upload as a directory as a single file? aft.setExplodeBeforeUpload(uploadAsDirectory); // set the parameters aft.setTitle(title); aft.setDescription(description); aft.setUseRemoteReplication(useRemoteRep); aft.setSkipExistingChunk(skipExistingChunks); if (passphrase != null && !passphrase.equals("")) { aft.setPassphrase(passphrase); } if (servers != null && servers.size() > 0) { for (String server : servers) { aft.addServerURL(server); } } status = STATUS_UPLOADING; // there should only be one file - either a file or a directory hash = aft.addFile(uploadedFile); // register the upload with proteomecommons if desired if (register) { status = STATUS_REGISTERING; try { // flag for registered boolean registered = false; // try to register for (int registerAttempt = 0; registerAttempt < 3; registerAttempt++) { // keep track of the status code final int[] statusCode = new int[1]; // spawn registration in a thread so it can be timed out Thread t = new Thread() { public void run() { try { // if the passphrase is null, save it as "" String p = passphrase; if (p == null) { p = ""; // make a new client } HttpClient c = new HttpClient(); // make a post method PostMethod pm = new PostMethod( "http://www.proteomecommons.org/dev/tranche/register.jsp"); NameValuePair b = new NameValuePair("hash", hash.toString()); NameValuePair a = new NameValuePair("passphrase", p); // set the values pm.setRequestBody(new NameValuePair[] { a, b }); // execute the method statusCode[0] = c.executeMethod(pm); // release the connection pm.releaseConnection(); } catch (Exception e) { // do nothing } } }; t.start(); // wait for up to 45 seconds t.join(45 * 1000); // pitch an exception if (t.isAlive() || statusCode[0] != 200) { throw new Exception("Can't register upload on ProteomeCommons.org"); } break; } } catch (Exception e) { // do nothing } } status = STATUS_COMPLETED; } catch (Exception e) { exception = e; status = STATUS_FAILED; } }
From source file:org.roda.wui.filter.CasClient.java
/** * Get a <strong>Ticket Granting Ticket</strong> from the CAS server for the * specified <i>username</i> and <i>password</i>. * // ww w . j av a2 s. co m * @param username * the username. * @param password * the password. * @return the <strong>Ticket Granting Ticket</strong> * @throws AuthenticationDeniedException * if the CAS server rejected the specified credentials. * @throws GenericException * if some error occurred. */ public String getTicketGrantingTicket(final String username, final String password) throws AuthenticationDeniedException, GenericException { final HttpClient client = new HttpClient(); final PostMethod post = new PostMethod(String.format("%s/v1/tickets", this.casServerUrlPrefix)); post.setRequestBody(new NameValuePair[] { new NameValuePair("username", username), new NameValuePair("password", password) }); try { client.executeMethod(post); final String response = post.getResponseBodyAsString(); if (post.getStatusCode() == HttpStatus.SC_CREATED) { final Matcher matcher = Pattern.compile(".*action=\".*/(.*?)\".*").matcher(response); if (matcher.matches()) { return matcher.group(1); } LOGGER.warn(NO_TICKET); throw new GenericException(NO_TICKET); } else if (post.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { throw new AuthenticationDeniedException("Could not create ticket: " + post.getStatusText()); } else { LOGGER.warn(invalidResponseMessage(post)); throw new GenericException(invalidResponseMessage(post)); } } catch (final IOException e) { throw new GenericException(e.getMessage(), e); } finally { post.releaseConnection(); } }