Java Code Examples for org.apache.commons.httpclient.methods.PostMethod#setRequestBody()
The following examples show how to use
org.apache.commons.httpclient.methods.PostMethod#setRequestBody() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractSubmarineServerTest.java From submarine with Apache License 2.0 | 7 votes |
protected static PostMethod httpPost(String path, String request, String mediaType, String user, String pwd) throws IOException { LOG.info("Connecting to {}", URL + path); HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(URL + path); postMethod.setRequestBody(request); postMethod.setRequestHeader("Content-type", mediaType); postMethod.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); if (userAndPasswordAreNotBlank(user, pwd)) { postMethod.setRequestHeader("Cookie", "JSESSIONID=" + getCookie(user, pwd)); } httpClient.executeMethod(postMethod); LOG.info("{} - {}", postMethod.getStatusCode(), postMethod.getStatusText()); return postMethod; }
Example 2
Source File: HttpClientUtil.java From javabase with Apache License 2.0 | 6 votes |
/** * 向目标发出一个Post请求并得到响应数据 * @param url * 目标 * @param params * 参数集合 * @param timeout * 超时时间 * @return 响应数据 * @throws IOException */ public static String sendPost(String url, NameValuePair[] data, int timeout) throws Exception { log.info("url:" + url); PostMethod method = new PostMethod(url); method.setRequestBody(data); method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8"); byte[] content; String text = null, charset = null; try { content = executeMethod(method, timeout); charset = method.getResponseCharSet(); text = new String(content, charset); log.info("post return:" + text); } catch (Exception e) { throw e; } finally { method.releaseConnection(); } return text; }
Example 3
Source File: CiscoVnmcConnectionImpl.java From cloudstack with Apache License 2.0 | 6 votes |
private String sendRequest(String service, String xmlRequest) throws ExecutionException { HttpClient client = new HttpClient(); String response = null; PostMethod method = new PostMethod("/xmlIM/" + service); method.setRequestBody(xmlRequest); try { org.apache.commons.httpclient.protocol.Protocol myhttps = new org.apache.commons.httpclient.protocol.Protocol("https", new EasySSLProtocolSocketFactory(), 443); client.getHostConfiguration().setHost(_ip, 443, myhttps); int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new Exception("Error code : " + statusCode); } response = method.getResponseBodyAsString(); } catch (Exception e) { System.out.println(e.getMessage()); throw new ExecutionException(e.getMessage()); } System.out.println(response); return response; }
Example 4
Source File: VmRuntimeJettyKitchenSink2Test.java From appengine-java-vm-runtime with Apache License 2.0 | 6 votes |
/** * Test that blob upload requests are intercepted by the blob upload filter. * * @throws Exception */ public void testBlobUpload() throws Exception { String postData = "--==boundary\r\n" + "Content-Type: message/external-body; " + "charset=ISO-8859-1; blob-key=\"blobkey:blob-0\"\r\n" + "Content-Disposition: form-data; " + "name=upload-0; filename=\"file-0.jpg\"\r\n" + "\r\n" + "Content-Type: image/jpeg\r\n" + "Content-Length: 1024\r\n" + "X-AppEngine-Upload-Creation: 2009-04-30 17:12:51.675929\r\n" + "Content-Disposition: form-data; " + "name=upload-0; filename=\"file-0.jpg\"\r\n" + "\r\n" + "\r\n" + "--==boundary\r\n" + "Content-Type: text/plain; charset=ISO-8859-1\r\n" + "Content-Disposition: form-data; name=text1\r\n" + "Content-Length: 10\r\n" + "\r\n" + "Testing.\r\n" + "\r\n" + "\r\n" + "--==boundary--"; HttpClient httpClient = new HttpClient(); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000); PostMethod blobPost = new PostMethod(createUrl("/upload-blob").toString()); blobPost.addRequestHeader("Content-Type", "multipart/form-data; boundary=\"==boundary\""); blobPost.addRequestHeader("X-AppEngine-BlobUpload", "true"); blobPost.setRequestBody(postData); int httpCode = httpClient.executeMethod(blobPost); assertEquals(302, httpCode); Header redirUrl = blobPost.getResponseHeader("Location"); assertEquals("http://" + getServerHost() + "/serve-blob?key=blobkey:blob-0", redirUrl.getValue()); }
Example 5
Source File: RefreshTokenAuthentication.java From JavaChatterRESTApi with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * <p>Using a valid Refresh token we can get a new accessToken.</p> * * @return The response retrieved from the REST API (usually an XML string with all the tokens) * @throws IOException * @throws UnauthenticatedSessionException */ @Override public ChatterAuthToken authenticate() throws IOException, UnauthenticatedSessionException, AuthenticationException { String authenticationUrl = "TEST".equalsIgnoreCase(chatterData.getEnvironment()) ? TEST_AUTHENTICATION_URL : PRODUCTION_AUTHENTICATION_URL; PostMethod post = new PostMethod(authenticationUrl); String clientId = URLEncoder.encode(chatterData.getClientKey(), "UTF-8"); String clientSecret = URLEncoder.encode(chatterData.getClientSecret(), "UTF-8"); NameValuePair[] data = { new NameValuePair("grant_type", "refresh_token"), new NameValuePair("client_id", clientId), new NameValuePair("client_secret", clientSecret), new NameValuePair("refresh_token", chatterData.getRefreshToken()) }; post.setRequestBody(data); int statusCode = getHttpClient().executeMethod(post); if (statusCode == HttpStatus.SC_OK) { return processResponse(post.getResponseBodyAsString()); } throw new UnauthenticatedSessionException(statusCode + " " + post.getResponseBodyAsString()); }
Example 6
Source File: SlackMessage.java From build-notifications-plugin with MIT License | 6 votes |
public void send() { String[] ids = channelIds.split("\\s*,\\s*"); HttpClient client = new HttpClient(); for (String channelId : ids) { PostMethod post = new PostMethod( "https://slack.com/api/chat.postMessage" ); post.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8"); post.setRequestBody(new NameValuePair[]{ new NameValuePair("token",botToken), new NameValuePair("as_user","true"), new NameValuePair("channel", channelId), new NameValuePair("text", getMessage()) }); try { client.executeMethod(post); } catch (IOException e) { LOGGER.severe("Error while sending notification: " + e.getMessage()); e.printStackTrace(); } } }
Example 7
Source File: PushoverMessage.java From build-notifications-plugin with MIT License | 6 votes |
@Override public void send() { HttpClient client = new HttpClient(); PostMethod post = new PostMethod("https://api.pushover.net/1/messages.json"); post.setRequestBody(new NameValuePair[]{ new NameValuePair("token", appToken), new NameValuePair("user", userToken), new NameValuePair("message", content + "\n\n" + extraMessage), new NameValuePair("title", title), new NameValuePair("priority", priority.toString()), new NameValuePair("url", url), new NameValuePair("url_title", urlTitle) }); try { client.executeMethod(post); } catch (IOException e) { LOGGER.severe("Error while sending notification: " + e.getMessage()); e.printStackTrace(); } }
Example 8
Source File: UsernamePasswordAuthentication.java From JavaChatterRESTApi with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * <p>Authenticate using a username and password. This is discouraged by the oauth flow, * but it allows for transparent (and non human-intervention) authentication).</p> * * @return The response retrieved from the REST API (usually an XML string with all the tokens) * @throws IOException * @throws UnauthenticatedSessionException * @throws AuthenticationException */ public ChatterAuthToken authenticate() throws IOException, UnauthenticatedSessionException, AuthenticationException { String clientId = URLEncoder.encode(chatterData.getClientKey(), "UTF-8"); String clientSecret = chatterData.getClientSecret(); String username = chatterData.getUsername(); String password = chatterData.getPassword(); String authenticationUrl = "TEST".equalsIgnoreCase(chatterData.getEnvironment()) ? TEST_AUTHENTICATION_URL : PRODUCTION_AUTHENTICATION_URL; PostMethod post = new PostMethod(authenticationUrl); NameValuePair[] data = { new NameValuePair("grant_type", "password"), new NameValuePair("client_id", clientId), new NameValuePair("client_secret", clientSecret), new NameValuePair("username", username), new NameValuePair("password", password) }; post.setRequestBody(data); int statusCode = getHttpClient().executeMethod(post); if (statusCode == HttpStatus.SC_OK) { return processResponse(post.getResponseBodyAsString()); } throw new UnauthenticatedSessionException(statusCode + " " + post.getResponseBodyAsString()); }
Example 9
Source File: ClientSecretAuthentication.java From JavaChatterRESTApi with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * <p>Authenticate using a client Secret. This is usually gotten by either asking the user, * or by using a callback. This allows for transparent (and non human-intervention) authentication.</p> * * @return The response retrieved from the REST API (usually an XML string with all the tokens) * @throws IOException * @throws UnauthenticatedSessionException * @throws AuthenticationException */ public ChatterAuthToken authenticate() throws IOException, UnauthenticatedSessionException, AuthenticationException { String clientId = chatterData.getClientKey(); String clientSecret = chatterData.getClientSecret(); String clientRedirect = chatterData.getClientCallback(); String clientCode = this.clientCode; if (null == clientCode && null != chatterData.getClientCode()) { clientCode = chatterData.getClientCode(); } String authenticationUrl = "TEST".equalsIgnoreCase(chatterData.getEnvironment()) ? TEST_AUTHENTICATION_URL : PRODUCTION_AUTHENTICATION_URL; PostMethod post = new PostMethod(authenticationUrl); NameValuePair[] data = { new NameValuePair("grant_type", "authorization_code"), new NameValuePair("client_id", clientId), new NameValuePair("client_secret", clientSecret), new NameValuePair("redirect_uri", clientRedirect), new NameValuePair("code", clientCode) }; post.setRequestBody(data); int statusCode = getHttpClient().executeMethod(post); if (statusCode == HttpStatus.SC_OK) { return processResponse(post.getResponseBodyAsString()); } throw new UnauthenticatedSessionException(statusCode + " " + post.getResponseBodyAsString()); }
Example 10
Source File: OldHttpClientApi.java From javabase with Apache License 2.0 | 6 votes |
public void post(){ String requesturl = "http://www.tuling123.com/openapi/api"; PostMethod postMethod = new PostMethod(requesturl); String APIKEY = "4b441cb500f431adc6cc0cb650b4a5d0"; String INFO ="北京时间"; NameValuePair nvp1=new NameValuePair("key",APIKEY); NameValuePair nvp2=new NameValuePair("info",INFO); NameValuePair[] data = new NameValuePair[2]; data[0]=nvp1; data[1]=nvp2; postMethod.setRequestBody(data); postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8"); try { byte[] responseBody = executeMethod(postMethod,10000); String content=new String(responseBody ,"utf-8"); log.info(content); }catch (Exception e){ log.error(""+e.getLocalizedMessage()); }finally { postMethod.releaseConnection(); } }
Example 11
Source File: GDataAuthStrategy.java From rome with Apache License 2.0 | 6 votes |
private void init() throws ProponoException { try { final HttpClient httpClient = new HttpClient(); final PostMethod method = new PostMethod("https://www.google.com/accounts/ClientLogin"); final NameValuePair[] data = { new NameValuePair("Email", email), new NameValuePair("Passwd", password), new NameValuePair("accountType", "GOOGLE"), new NameValuePair("service", service), new NameValuePair("source", "ROME Propono Atompub Client") }; method.setRequestBody(data); httpClient.executeMethod(method); final String responseBody = method.getResponseBodyAsString(); final int authIndex = responseBody.indexOf("Auth="); authToken = "GoogleLogin auth=" + responseBody.trim().substring(authIndex + 5); } catch (final Throwable t) { t.printStackTrace(); throw new ProponoException("ERROR obtaining Google authentication string", t); } }
Example 12
Source File: CSP.java From scim2-compliance-test-suite with Apache License 2.0 | 5 votes |
public String getAccessTokenUserPass() { if (!StringUtils.isEmpty(this.oAuth2AccessToken)) { return this.oAuth2AccessToken; } if (StringUtils.isEmpty(this.username) || StringUtils.isEmpty(this.password) && StringUtils.isEmpty(this.oAuth2AuthorizationServer) || StringUtils.isEmpty(this.oAuth2ClientId) || StringUtils.isEmpty(this.oAuth2ClientSecret)) { return ""; } try { HttpClient client = new HttpClient(); client.getParams().setAuthenticationPreemptive(true); // post development PostMethod method = new PostMethod(this.getOAuthAuthorizationServer()); method.setRequestHeader(new Header("Content-type", "application/x-www-form-urlencoded")); method.addRequestHeader("Authorization", "Basic " + Base64.encodeBase64String((username + ":" + password).getBytes())); NameValuePair[] body = new NameValuePair[] { new NameValuePair("username", username), new NameValuePair("password", password), new NameValuePair("client_id", oAuth2ClientId), new NameValuePair("client_secret", oAuth2ClientSecret), new NameValuePair("grant_type", oAuth2GrantType) }; method.setRequestBody(body); int responseCode = client.executeMethod(method); String responseBody = method.getResponseBodyAsString(); if (responseCode != 200) { throw new RuntimeException("Failed to fetch access token form authorization server, " + this.getOAuthAuthorizationServer() + ", got response code " + responseCode); } JSONObject accessResponse = new JSONObject(responseBody); accessResponse.getString("access_token"); return (this.oAuth2AccessToken = accessResponse.getString("access_token")); } catch (Exception e) { throw new RuntimeException("Failed to read response from authorizationServer at " + this.getOAuthAuthorizationServer(), e); } }
Example 13
Source File: CSP.java From scim2-compliance-test-suite with Apache License 2.0 | 5 votes |
@SuppressWarnings("deprecation") public String getAccessToken() { if (this.oAuth2AccessToken != null) { return this.oAuth2AccessToken; } try { HttpClient client = new HttpClient(); client.getParams().setAuthenticationPreemptive(true); Credentials defaultcreds = new UsernamePasswordCredentials(this.getUsername(), this.getPassword()); client.getState().setCredentials(AuthScope.ANY, defaultcreds); PostMethod method = new PostMethod(this.getOAuthAuthorizationServer()); method.setRequestBody("grant_type=client_credentials"); int responseCode = client.executeMethod(method); if (responseCode != 200) { throw new RuntimeException("Failed to fetch access token form authorization server, " + this.getOAuthAuthorizationServer() + ", got response code " + responseCode); } String responseBody = method.getResponseBodyAsString(); JSONObject accessResponse = new JSONObject(responseBody); accessResponse.getString("access_token"); return (this.oAuth2AccessToken = accessResponse.getString("access_token")); } catch (Exception e) { throw new RuntimeException("Failed to read response from authorizationServer at " + this.getOAuthAuthorizationServer(), e); } }
Example 14
Source File: AbstractTestRestApi.java From zeppelin with Apache License 2.0 | 5 votes |
protected static PostMethod httpPost(String path, String request, String user, String pwd) throws IOException { LOG.info("Connecting to {}", URL + path); HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(URL + path); postMethod.setRequestBody(request); postMethod.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); if (userAndPasswordAreNotBlank(user, pwd)) { postMethod.setRequestHeader("Cookie", "JSESSIONID=" + getCookie(user, pwd)); } httpClient.executeMethod(postMethod); LOG.info("{} - {}", postMethod.getStatusCode(), postMethod.getStatusText()); return postMethod; }
Example 15
Source File: ZeppelinServerMock.java From zeppelin with Apache License 2.0 | 5 votes |
protected static PostMethod httpPost(String path, String request, String user, String pwd) throws IOException { LOG.info("Connecting to {}", URL + path); HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(URL + path); postMethod.setRequestBody(request); postMethod.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); if (userAndPasswordAreNotBlank(user, pwd)) { postMethod.setRequestHeader("Cookie", "JSESSIONID=" + getCookie(user, pwd)); } httpClient.executeMethod(postMethod); LOG.info("{} - {}", postMethod.getStatusCode(), postMethod.getStatusText()); return postMethod; }
Example 16
Source File: ChuangRuiSMSProvider.java From ZTuoExchange_framework with MIT License | 5 votes |
public MessageResult sendMessage(String mobile, String content,SmsDTO smsDTO) throws Exception{ log.info("sms content={}", content); HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod("http://api.1cloudsp.com/api/v2/single_send"); postMethod.getParams().setContentCharset("UTF-8"); postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); NameValuePair[] data = { new NameValuePair("accesskey", smsDTO.getKeyId()), new NameValuePair("secret", smsDTO.getKeySecret()), new NameValuePair("sign", smsDTO.getSignId()), new NameValuePair("templateId", smsDTO.getTemplateId()), new NameValuePair("mobile", mobile), new NameValuePair("content", URLEncoder.encode(content, "utf-8"))//(发送的短信内容是模板变量内容,多个变量中间用##或者$$隔开,采用utf8编码) }; postMethod.setRequestBody(data); int statusCode = httpClient.executeMethod(postMethod); System.out.println("statusCode: " + statusCode + ", body: " + postMethod.getResponseBodyAsString()); log.info(" mobile : " + mobile + "content : " + content); log.info("statusCode: " + statusCode + ", body: " + postMethod.getResponseBodyAsString()); return parseResult(postMethod.getResponseBodyAsString()); }
Example 17
Source File: ChuangRuiSMSProvider.java From ZTuoExchange_framework with MIT License | 5 votes |
public MessageResult sendMessage(String mobile, String content,SmsDTO smsDTO) throws Exception{ log.info("sms content={}", content); HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod("http://api.1cloudsp.com/api/v2/single_send"); postMethod.getParams().setContentCharset("UTF-8"); postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); NameValuePair[] data = { new NameValuePair("accesskey", smsDTO.getKeyId()), new NameValuePair("secret", smsDTO.getKeySecret()), new NameValuePair("sign", smsDTO.getSignId()), new NameValuePair("templateId", smsDTO.getTemplateId()), new NameValuePair("mobile", mobile), new NameValuePair("content", URLEncoder.encode(content, "utf-8"))//(发送的短信内容是模板变量内容,多个变量中间用##或者$$隔开,采用utf8编码) }; postMethod.setRequestBody(data); int statusCode = httpClient.executeMethod(postMethod); System.out.println("statusCode: " + statusCode + ", body: " + postMethod.getResponseBodyAsString()); log.info(" mobile : " + mobile + "content : " + content); log.info("statusCode: " + statusCode + ", body: " + postMethod.getResponseBodyAsString()); return parseResult(postMethod.getResponseBodyAsString()); }
Example 18
Source File: BaseHttpRequestMaker.java From MesquiteCore with GNU Lesser General Public License v3.0 | 5 votes |
public static byte[] doPost(String url, Map additionalParameters) { PostMethod xmlPost = new PostMethod(url); NameValuePair[] argsArray = new NameValuePair[additionalParameters.keySet().size()]; int i = 0; for (Iterator iter = additionalParameters.keySet().iterator(); iter.hasNext();) { String nextParamName = (String) iter.next(); String nextValue = (String) additionalParameters.get(nextParamName); argsArray[i++] = new NameValuePair(nextParamName, nextValue); } xmlPost.setRequestBody(argsArray); return executePost(xmlPost); }
Example 19
Source File: HuaXinSMSProvider.java From ZTuoExchange_framework with MIT License | 4 votes |
@Override public MessageResult sendInternationalMessage(String content, String phone) throws IOException, DocumentException { content=String.format("[%s]Verification Code:%s.If you do not send it, please ignore this message.", sign,content); HttpClient client = new HttpClient(); PostMethod method = new PostMethod(internationalGateway); String result = encodeHexStr(8, content); client.getParams().setContentCharset("UTF-8"); method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8"); NameValuePair[] data = {new NameValuePair("action", "send"), new NameValuePair("userid", ""), new NameValuePair("account", internationalUsername), new NameValuePair("password", internationalPassword), new NameValuePair("mobile", phone), //发英文 用 0 其他中日韩 用 8 new NameValuePair("code", "8"), new NameValuePair("content", result), new NameValuePair("sendTime", ""), new NameValuePair("extno", ""),}; method.setRequestBody(data); client.executeMethod(method); String response = method.getResponseBodyAsString(); Document doc = DocumentHelper.parseText(response); // 获取根节点 Element rootElt = doc.getRootElement(); // 获取根节点下的子节点的值 String returnstatus = rootElt.elementText("returnstatus").trim(); String message = rootElt.elementText("message").trim(); String remainpoint = rootElt.elementText("balance").trim(); String taskID = rootElt.elementText("taskID").trim(); String successCounts = rootElt.elementText("successCounts").trim(); System.out.println(response); System.out.println("返回状态为:" + returnstatus); System.out.println("返回信息提示:" + message); System.out.println("返回余额:" + remainpoint); System.out.println("返回任务批次:" + taskID); System.out.println("返回成功条数:" + successCounts); MessageResult messageResult = MessageResult.success(); if (!"Success".equals(returnstatus)) { messageResult.setCode(500); } messageResult.setMessage(message); return messageResult; }
Example 20
Source File: HuaXinSMSProvider.java From ZTuoExchange_framework with MIT License | 4 votes |
@Override public MessageResult sendInternationalMessage(String content, String phone) throws IOException, DocumentException { content=String.format("[%s]Verification Code:%s.If you do not send it, please ignore this message.", sign,content); HttpClient client = new HttpClient(); PostMethod method = new PostMethod(internationalGateway); String result = encodeHexStr(8, content); client.getParams().setContentCharset("UTF-8"); method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8"); NameValuePair[] data = {new NameValuePair("action", "send"), new NameValuePair("userid", ""), new NameValuePair("account", internationalUsername), new NameValuePair("password", internationalPassword), new NameValuePair("mobile", phone), //发英文 用 0 其他中日韩 用 8 new NameValuePair("code", "8"), new NameValuePair("content", result), new NameValuePair("sendTime", ""), new NameValuePair("extno", ""),}; method.setRequestBody(data); client.executeMethod(method); String response = method.getResponseBodyAsString(); Document doc = DocumentHelper.parseText(response); // 获取根节点 Element rootElt = doc.getRootElement(); // 获取根节点下的子节点的值 String returnstatus = rootElt.elementText("returnstatus").trim(); String message = rootElt.elementText("message").trim(); String remainpoint = rootElt.elementText("balance").trim(); String taskID = rootElt.elementText("taskID").trim(); String successCounts = rootElt.elementText("successCounts").trim(); System.out.println(response); System.out.println("返回状态为:" + returnstatus); System.out.println("返回信息提示:" + message); System.out.println("返回余额:" + remainpoint); System.out.println("返回任务批次:" + taskID); System.out.println("返回成功条数:" + successCounts); MessageResult messageResult = MessageResult.success(); if (!"Success".equals(returnstatus)) { messageResult.setCode(500); } messageResult.setMessage(message); return messageResult; }