List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestBody
public void setRequestBody(NameValuePair[] paramArrayOfNameValuePair) throws IllegalArgumentException
From source file:com.touch6.sm.gateway.webchinese.Webchinese.java
public static String batchSend(String url, String uid, String key, String phone, String msg, String contentType, String charset) throws CoreException { HttpClient client = new HttpClient(); PostMethod post = new PostMethod(url); post.addRequestHeader("Content-Type", contentType);//? NameValuePair[] data = { new NameValuePair("Uid", uid), new NameValuePair("Key", key), new NameValuePair("smsMob", phone), new NameValuePair("smsText", msg) }; post.setRequestBody(data); try {// w ww .jav a 2 s. com client.executeMethod(post); } catch (Exception e) { logger.info("??:", e); throw new CoreException(ECodeUtil.getCommError(SystemErrorConstant.SYSTEM_EXCEPTION)); } Header[] headers = post.getResponseHeaders(); int statusCode = post.getStatusCode(); System.out.println("statusCode:" + statusCode); for (Header h : headers) { System.out.println(h.toString()); } String result; try { result = new String(post.getResponseBodyAsString().getBytes(charset)); System.out.println(result); //??? } catch (Exception e) { logger.info("??:", e); throw new CoreException(ECodeUtil.getCommError(SystemErrorConstant.SYSTEM_EXCEPTION)); } post.releaseConnection(); return result; }
From source file:com.feilong.tools.net.httpclient3.HttpClientUtil.java
/** * uri and params./*from w w w . ja v a 2s . c om*/ * * @param httpClientConfig * the uri and params * @return the http method * @since 1.0.9 */ private static HttpMethod setUriAndParams(HttpClientConfig httpClientConfig) { String uri = httpClientConfig.getUri(); Map<String, String> params = httpClientConfig.getParams(); NameValuePair[] nameValuePairs = null; if (Validator.isNotNullOrEmpty(params)) { nameValuePairs = NameValuePairUtil.fromMap(params); } HttpMethodType httpMethodType = httpClientConfig.getHttpMethodType(); switch (httpMethodType) { case GET: // get GetMethod getMethod = new GetMethod(uri); //TODO ?? uri?? nameValuePairs if (Validator.isNotNullOrEmpty(nameValuePairs) && uri.indexOf("?") != -1) { throw new NotImplementedException("not implemented!"); } if (Validator.isNotNullOrEmpty(nameValuePairs)) { getMethod.setQueryString(nameValuePairs); } return getMethod; case POST: // post PostMethod postMethod = new PostMethod(uri); if (Validator.isNotNullOrEmpty(nameValuePairs)) { postMethod.setRequestBody(nameValuePairs); } return postMethod; default: throw new UnsupportedOperationException("httpMethod:[" + httpMethodType + "] not support!"); } }
From source file:com.dotmarketing.util.UpdateUtil.java
/** * @return the new version if found. Null if up to date. * @throws DotDataException if an error is encountered *///w ww . ja v a 2s . c om public static String getNewVersion() throws DotDataException { //Loading the update url Properties props = loadUpdateProperties(); String fileUrl = props.getProperty(Constants.PROPERTY_UPDATE_FILE_UPDATE_URL, ""); Map<String, String> pars = new HashMap<String, String>(); pars.put("version", ReleaseInfo.getVersion()); //pars.put("minor", ReleaseInfo.getBuildNumber() + ""); pars.put("check_version", "true"); pars.put("level", System.getProperty("dotcms_level")); if (System.getProperty("dotcms_license_serial") != null) { pars.put("license", System.getProperty("dotcms_license_serial")); } HttpClient client = new HttpClient(); PostMethod method = new PostMethod(fileUrl); Object[] keys = (Object[]) pars.keySet().toArray(); NameValuePair[] data = new NameValuePair[keys.length]; for (int i = 0; i < keys.length; i++) { String key = (String) keys[i]; NameValuePair pair = new NameValuePair(key, pars.get(key)); data[i] = pair; } method.setRequestBody(data); String ret = null; try { client.executeMethod(method); int retCode = method.getStatusCode(); if (retCode == 204) { Logger.info(UpdateUtil.class, "No new updates found"); } else { if (retCode == 200) { String newMinor = method.getResponseHeader("Minor-Version").getValue(); String newPrettyName = null; if (method.getResponseHeader("Pretty-Name") != null) { newPrettyName = method.getResponseHeader("Pretty-Name").getValue(); } if (newPrettyName == null) { Logger.info(UpdateUtil.class, "New Version: " + newMinor); ret = newMinor; } else { Logger.info(UpdateUtil.class, "New Version: " + newPrettyName + "/" + newMinor); ret = newPrettyName; } } else { throw new DotDataException( "Unknown return code: " + method.getStatusCode() + " (" + method.getStatusText() + ")"); } } } catch (HttpException e) { Logger.error(UpdateUtil.class, "HttpException: " + e.getMessage(), e); throw new DotDataException("HttpException: " + e.getMessage(), e); } catch (IOException e) { Logger.error(UpdateUtil.class, "IOException: " + e.getMessage(), e); throw new DotDataException("IOException: " + e.getMessage(), e); } return ret; }
From source file:edu.utah.further.core.ws.HttpUtil.java
/** * @param url/* w ww . j a v a2 s . c o m*/ * @param data * @return */ public static PostMethod createPostMethod(final String url, final NameValuePair[] data) { final PostMethod method = new PostMethod(url); //method.addRequestHeader(HttpHeader.CONTENT_TYPE.getName(), "text/plain"); method.setRequestBody(data); // Provide custom retry handler is necessary return method; }
From source file:com.zimbra.cs.util.WebClientServiceUtil.java
public static void sendDeployZimletRequestToUiNode(Server server, String zimlet, String authToken, byte[] data) throws ServiceException { if (isServerAtLeast8dot5(server)) { HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient(); HttpProxyUtil.configureProxy(client); PostMethod method = new PostMethod(URLUtil.getServiceURL(server, "/fromservice/deployzimlet", false)); method.addRequestHeader(ZimletUtil.PARAM_ZIMLET, zimlet); ZimbraLog.zimlet.info("connecting to ui node %s, data size %d", server.getName(), data.length); method.setRequestBody(new ByteArrayInputStream(data)); postToUiNode(server, method, authToken); }/*from w ww.ja va 2s . c o m*/ }
From source file:it.eng.spagobi.engines.talend.client.SpagoBITalendEngineClient.java
public static String getEngineComplianceVersion(String url) throws EngineUnavailableException, ServiceInvocationFailedException { String version;/*from www . jav a 2s . c o m*/ HttpClient client; PostMethod method; NameValuePair[] nameValuePairs; version = null; client = new HttpClient(); method = new PostMethod(url); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); nameValuePairs = new NameValuePair[] { new NameValuePair("infoType", "complianceVersion") }; //$NON-NLS-1$ //$NON-NLS-2$ method.setRequestBody(nameValuePairs); try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new ServiceInvocationFailedException( Messages.getString("SpagoBITalendEngineClient.serviceFailed"), //$NON-NLS-1$ method.getStatusLine().toString(), method.getResponseBodyAsString()); } else { version = method.getResponseBodyAsString(); } } catch (HttpException e) { throw new EngineUnavailableException(Messages.getString("SpagoBITalendEngineClient.5", e.getMessage())); //$NON-NLS-1$ } catch (IOException e) { throw new EngineUnavailableException(Messages.getString("SpagoBITalendEngineClient.6", e.getMessage())); //$NON-NLS-1$ } finally { // Release the connection. method.releaseConnection(); } return version; }
From source file:com.leosys.core.utils.SendMessage.java
public static String postMessage(String phoneNo, String sendText) throws IOException { HttpClient client = new HttpClient(); PostMethod post = new PostMethod("http://sms.webchinese.cn/web_api/"); post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=gbk");// ? NameValuePair[] data = { new NameValuePair("Uid", "fanyy"), // ?? new NameValuePair("Key", "694de3e5ca9f7015eaef"), // ??, new NameValuePair("smsMob", phoneNo), // ?? new NameValuePair("smsText", sendText + "??") };// post.setRequestBody(data); client.executeMethod(post);//from ww w .j a v a 2 s. co m Header[] headers = post.getResponseHeaders(); int statusCode = post.getStatusCode(); System.out.println("statusCode:" + statusCode); for (Header h : headers) { System.out.println(h.toString()); } String result = new String(post.getResponseBodyAsString().getBytes("gbk")); System.out.println(result); post.releaseConnection(); return result; }
From source file:edu.ku.brc.af.tasks.StatsTrackerTask.java
/** * Connects to the update/usage tracking server to get the latest version info and/or send the usage stats. * @param url//from ww w. ja v a 2 s . co m * @param postParams * @param userAgentName * @throws Exception if an IO error occurred or the response couldn't be parsed */ public static void sendStats(final String url, final Vector<NameValuePair> postParams, final String userAgentName) throws Exception { // System.out.println("--------------------"); // for (NameValuePair nvp : postParams) // { // System.out.println(String.format("[%s][%s]", nvp.getName(), nvp.getValue())); // } // System.out.println("--------------------"); // If the user changes collection before it gets a chance to send the stats //if (!AppContextMgr.getInstance().hasContext()) return; // check the website for the info about the latest version HttpClient httpClient = new HttpClient(); httpClient.getParams().setParameter("http.useragent", userAgentName); //$NON-NLS-1$ PostMethod postMethod = new PostMethod(url); // get the POST parameters (which includes usage stats, if we're allowed to send them) postMethod.setRequestBody(buildNamePairArray(postParams)); // connect to the server try { httpClient.executeMethod(postMethod); // get the server response @SuppressWarnings("unused") String responseString = postMethod.getResponseBodyAsString(); //if (StringUtils.isNotEmpty(responseString)) //{ // System.err.println(responseString); //} } catch (java.net.UnknownHostException ex) { log.debug("Couldn't reach host."); } catch (Exception e) { //e.printStackTrace(); //UsageTracker.incrHandledUsageCount(); //edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(StatsTrackerTask.class, e); throw new ConnectionException(e); } }
From source file:edu.utah.further.core.ws.HttpUtil.java
/** * Create an HTTP POST method with a string body. This calls the deprecated * {@link PostMethod#setRequestBody(String)}, but since we are not planning on using * newer version of the HttpClient library, and this was verified to work with version * 3.0.1 that matches i2b2's axis2 web application version, we add suppress the * deprecation warning here. If there's ever a problem, use * {@link #createPostMethod(String, NameValuePair[])} instead, which should require * only minor changes to the FURTHeR i2b2 hook and web service interface. * //from www .j a v a 2 s . c o m * @param url * target HTTP URL * @param body * POST body * @return HTTP POST method with the URL and body */ @SuppressWarnings("deprecation") public static PostMethod createPostMethod(final String url, final String body) { final PostMethod method = new PostMethod(url); // Set both upper and lower case headers, just in case method.addRequestHeader(HttpHeader.CONTENT_TYPE.getName(), "application/xml"); method.addRequestHeader(HttpHeader.CONTENT_TYPE.getName().toLowerCase(), "application/xml"); method.setRequestBody(body); // Provide custom retry handler is necessary return method; }
From source file:net.bioclipse.opentox.api.Dataset.java
public static String createNewDataset(String service, String sdFile, IProgressMonitor monitor) throws Exception { if (monitor == null) monitor = new NullProgressMonitor(); HttpClient client = new HttpClient(); PostMethod method = new PostMethod(service + "dataset"); HttpMethodHelper.addMethodHeaders(method, new HashMap<String, String>() { {/* w w w . jav a2 s .c o m*/ put("Accept", "text/uri-list"); put("Content-type", "chemical/x-mdl-sdfile"); } }); System.out.println("Method: " + method.toString()); method.setRequestBody(sdFile); client.executeMethod(method); int status = method.getStatusCode(); String dataset = ""; String responseString = method.getResponseBodyAsString(); logger.debug("Response: " + responseString); int tailing = 1; if (status == 200 || status == 201 || status == 202) { if (responseString.contains("/task/")) { logger.debug("Task: " + responseString); // OK, we got a task... let's wait until it is done String task = method.getResponseBodyAsString(); Thread.sleep(1000); // let's be friendly, and wait 1 sec TaskState state = Task.getState(task); while (!state.isFinished() && !monitor.isCanceled()) { // let's be friendly, and wait 2 secs and a bit and increase // that time after each wait int waitingTime = andABit(2000 * tailing); logger.debug("Waiting " + waitingTime + "ms."); waitUnlessInterrupted(waitingTime, monitor); state = Task.getState(task); if (state.isRedirected()) { task = state.getResults(); logger.debug(" new task, new task!!: " + task); } // but wait at most 20 secs and a bit if (tailing < 10) tailing++; } if (monitor.isCanceled()) Task.delete(task); // OK, it should be finished now dataset = state.getResults(); } else { // OK, that was quick! dataset = method.getResponseBodyAsString(); logger.debug("No Task, Data set: " + dataset); } } method.releaseConnection(); if (monitor.isCanceled()) return ""; logger.debug("Data set: " + dataset); dataset = dataset.replaceAll("\n", ""); return dataset; }