List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestBody
public void setRequestBody(NameValuePair[] paramArrayOfNameValuePair) throws IllegalArgumentException
From source file:games.strategy.triplea.pbem.AxisAndAlliesForumPoster.java
/** * Logs into axisandallies.org//from w w w . ja v a2 s . co m * nb: Username and password are posted in clear text * * @throws Exception * if login fails */ private void login() throws Exception { // creates and configures a new http client m_client = new HttpClient(); m_client.getParams().setParameter("http.protocol.single-cookie-header", true); m_client.getParams().setParameter("http.useragent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)"); m_httpState = new HttpState(); m_hostConfiguration = new HostConfiguration(); // add the proxy GameRunner2.addProxy(m_hostConfiguration); m_hostConfiguration.setHost("www.axisandallies.org"); final PostMethod post = new PostMethod("http://www.axisandallies.org/forums/index.php?action=login2"); try { post.addRequestHeader("Accept", "*/*"); post.addRequestHeader("Accept-Language", "en-us"); post.addRequestHeader("Cache-Control", "no-cache"); post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded"); final List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new NameValuePair("user", getUsername())); parameters.add(new NameValuePair("passwrd", getPassword())); post.setRequestBody(parameters.toArray(new NameValuePair[parameters.size()])); int status = m_client.executeMethod(m_hostConfiguration, post, m_httpState); if (status == 200) { final String body = post.getResponseBodyAsString(); if (body.toLowerCase().contains("password incorrect")) { throw new Exception("Incorrect Password"); } // site responds with 200, and a refresh header final Header refreshHeader = post.getResponseHeader("Refresh"); if (refreshHeader == null) { throw new Exception("Missing refresh header after login"); } final String value = refreshHeader.getValue(); // refresh: 0; URL=http://... final Pattern p = Pattern.compile("[^;]*;\\s*url=(.*)", Pattern.DOTALL | Pattern.CASE_INSENSITIVE); final Matcher m = p.matcher(value); if (m.matches()) { final String url = m.group(1); final GetMethod getRefreshPage = new GetMethod(url); try { status = m_client.executeMethod(m_hostConfiguration, getRefreshPage, m_httpState); if (status != 200) { // something is probably wrong, but there is not much we can do about it, we handle errors when we post } } finally { getRefreshPage.releaseConnection(); } } else { throw new Exception("The refresh header didn't contain a URL"); } } else { throw new Exception("Failed to login to forum, server responded with status code: " + status); } } finally { post.releaseConnection(); } }
From source file:com.mirth.connect.connectors.http.HttpMessageDispatcher.java
private HttpMethod buildHttpRequest(String address, MessageObject mo) throws Exception { String method = connector.getDispatcherMethod(); String content = replacer.replaceValues(connector.getDispatcherContent(), mo); String contentType = connector.getDispatcherContentType(); String charset = connector.getDispatcherCharset(); boolean isMultipart = connector.isDispatcherMultipart(); Map<String, String> headers = replacer.replaceValuesInMap(connector.getDispatcherHeaders(), mo); Map<String, String> parameters = replacer.replaceValuesInMap(connector.getDispatcherParameters(), mo); HttpMethod httpMethod = null;// w w w. ja v a 2 s . c o m // populate the query parameters NameValuePair[] queryParameters = new NameValuePair[parameters.size()]; int index = 0; for (Entry<String, String> parameterEntry : parameters.entrySet()) { queryParameters[index] = new NameValuePair(parameterEntry.getKey(), parameterEntry.getValue()); index++; logger.debug("setting query parameter: [" + parameterEntry.getKey() + ", " + parameterEntry.getValue() + "]"); } // create the method if ("GET".equalsIgnoreCase(method)) { httpMethod = new GetMethod(address); httpMethod.setQueryString(queryParameters); } else if ("POST".equalsIgnoreCase(method)) { PostMethod postMethod = new PostMethod(address); if (isMultipart) { logger.debug("setting multipart file content"); File tempFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp"); FileUtils.writeStringToFile(tempFile, content, charset); Part[] parts = new Part[] { new FilePart(tempFile.getName(), tempFile, contentType, charset) }; postMethod.setQueryString(queryParameters); postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams())); } else if (StringUtils.equals(contentType, "application/x-www-form-urlencoded")) { postMethod.setRequestBody(queryParameters); } else { postMethod.setQueryString(queryParameters); postMethod.setRequestEntity(new StringRequestEntity(content, contentType, charset)); } httpMethod = postMethod; } else if ("PUT".equalsIgnoreCase(method)) { PutMethod putMethod = new PutMethod(address); putMethod.setRequestEntity(new StringRequestEntity(content, contentType, charset)); putMethod.setQueryString(queryParameters); httpMethod = putMethod; } else if ("DELETE".equalsIgnoreCase(method)) { httpMethod = new DeleteMethod(address); httpMethod.setQueryString(queryParameters); } // set the headers for (Entry<String, String> headerEntry : headers.entrySet()) { httpMethod.setRequestHeader(new Header(headerEntry.getKey(), headerEntry.getValue())); logger.debug("setting method header: [" + headerEntry.getKey() + ", " + headerEntry.getValue() + "]"); } return httpMethod; }
From source file:games.strategy.engine.random.PropertiesDiceRoller.java
public String postRequest(final int max, final int numDice, final String subjectMessage, String gameID, final String gameUUID) throws IOException { if (gameID.trim().length() == 0) gameID = "TripleA"; String message = gameID + ":" + subjectMessage; final int maxLength = Integer.valueOf(m_props.getProperty("message.maxlength")); if (message.length() > maxLength) message = message.substring(0, maxLength - 1); final PostMethod post = new PostMethod(m_props.getProperty("path")); final NameValuePair[] data = { new NameValuePair("numdice", "" + numDice), new NameValuePair("numsides", "" + max), new NameValuePair("modroll", "No"), new NameValuePair("numroll", "" + 1), new NameValuePair("subject", message), new NameValuePair("roller", getToAddress()), new NameValuePair("gm", getCcAddress()), new NameValuePair("send", "true"), }; post.setRequestHeader("User-Agent", "triplea/" + EngineVersion.VERSION); // this is to allow a dice server to allow the user to request the emails for the game // rather than sending out email for each roll post.setRequestHeader("X-Triplea-Game-UUID", gameUUID); post.setRequestBody(data); final HttpClient client = new HttpClient(); try {/*w ww . j av a 2s .com*/ final String host = m_props.getProperty("host"); int port = 80; if (m_props.getProperty("port") != null) { port = Integer.parseInt(m_props.getProperty("port")); } final HostConfiguration config = client.getHostConfiguration(); config.setHost(host, port); // add the proxy GameRunner2.addProxy(config); client.executeMethod(post); final String result = post.getResponseBodyAsString(); return result; } finally { post.releaseConnection(); } }
From source file:com.apifest.oauth20.tests.OAuth20BasicTest.java
public String obtainClientCredentialsAccessTokenResponse(String currentClientId, String currentClientSecret, String scope, boolean addAuthHeader) { PostMethod post = new PostMethod(baseOAuth20Uri + TOKEN_ENDPOINT); String response = null;// www .j a va 2 s .c om try { post.setRequestHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); if (addAuthHeader) { NameValuePair[] requestBody = { new NameValuePair(GRANT_TYPE_PARAM, GRANT_TYPE_CLIENT_CREDENTIALS), new NameValuePair(SCOPE_PARAM, scope) }; post.setRequestBody(requestBody); post.setRequestHeader(HttpHeaders.AUTHORIZATION, createBasicAuthorization(currentClientId, currentClientSecret)); } else { NameValuePair[] requestBody = { new NameValuePair(GRANT_TYPE_PARAM, GRANT_TYPE_CLIENT_CREDENTIALS), new NameValuePair(SCOPE_PARAM, scope), new NameValuePair(CLIENT_ID_PARAM, currentClientId), new NameValuePair(CLIENT_SECRET_PARAM, currentClientSecret) }; post.setRequestBody(requestBody); } response = readResponse(post); } catch (IOException e) { log.error("cannot obtain client credentials acces token response", e); } return response; }
From source file:com.taobao.diamond.client.impl.DefaultDiamondPublisher.java
private void login() throws Exception { PostMethod loginMethod = new PostMethod(getLoginUri()); NameValuePair username_value = new NameValuePair("username", userName); NameValuePair password_value = new NameValuePair("password", password); loginMethod.addRequestHeader(Constants.APPNAME, this.appName); loginMethod.setRequestBody(new NameValuePair[] { username_value, password_value }); this.configureHttpMethod(loginMethod); log.info("server list:" + this.diamondConfigure.getDomainNameList()); log.info("index=" + this.domainNamePos.get()); httpClient.getHostConfiguration().setHost(diamondConfigure.getDomainNameList().get(domainNamePos.get()), diamondConfigure.getPort()); try {//from w w w .ja v a2s.c o m int statusCode = httpClient.executeMethod(loginMethod); String responseMsg = loginMethod.getResponseBodyAsString(); if (statusCode == HttpStatus.SC_OK) { log.info(""); } else { log.error("" + responseMsg + ", " + statusCode); throw new Exception(", "); } } finally { loginMethod.releaseConnection(); } }
From source file:com.cloudmaster.cmp.util.AlarmSystem.transfer.HttpSender.java
public ResponseObject send(TransportObject object) throws Exception { ResponseObject rs = new ResponseObject(); ByteArrayOutputStream bOs = null; DataOutputStream dOs = null;/* ww w. jav a 2 s.c om*/ DataInputStream dIs = null; HttpClient client; PostMethod meth = null; byte[] rawData; try { bOs = new ByteArrayOutputStream(); dOs = new DataOutputStream(bOs); object.toStream(dOs); bOs.flush(); rawData = bOs.toByteArray(); client = new HttpClient(); client.setConnectionTimeout(this.timeout); client.setTimeout(this.datatimeout); client.setHttpConnectionFactoryTimeout(this.timeout); meth = new PostMethod(object.getValue(SERVER_URL)); // meth = new UTF8PostMethod(url); meth.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, ENCODING); // meth.addParameter(SERVER_ARGS, new String(rawData,"UTF-8")); // meth.setRequestBody(new String(rawData)); // meth.setRequestBody(new String(rawData,"UTF-8")); byte[] base64Array = Base64.encode(rawData).getBytes(); meth.setRequestBody(new String(base64Array)); // System.out.println(new String(rawData)); client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(1, false)); client.executeMethod(meth); dIs = new DataInputStream(meth.getResponseBodyAsStream()); if (meth.getStatusCode() == HttpStatus.SC_OK) { Header errHeader = meth.getResponseHeader(HDR_ERROR); if (errHeader != null) { rs.setError(meth.getResponseBodyAsString()); return rs; } rs = ResponseObject.fromStream(dIs); return rs; } else { meth.releaseConnection(); throw new IOException("Connection failure: " + meth.getStatusLine().toString()); } } finally { if (meth != null) { meth.releaseConnection(); } if (bOs != null) { bOs.close(); } if (dOs != null) { dOs.close(); } if (dIs != null) { dIs.close(); } } }
From source file:com.taobao.diamond.client.impl.DefaultDiamondPublisher.java
private void processUpdate(String dataId, String group, String content) throws Exception { PostMethod updateMethod = new PostMethod(getUpdateUri()); NameValuePair dataId_value = new NameValuePair("dataId", dataId); NameValuePair group_value = new NameValuePair("group", group); NameValuePair content_value = new NameValuePair("content", content); updateMethod.addRequestHeader(Constants.APPNAME, this.appName); updateMethod.setRequestBody(new NameValuePair[] { dataId_value, group_value, content_value }); this.configureHttpMethod(updateMethod); httpClient.getHostConfiguration().setHost(diamondConfigure.getDomainNameList().get(domainNamePos.get()), diamondConfigure.getPort()); try {//from w ww .j a va 2 s. c om int statusCode = httpClient.executeMethod(updateMethod); String responseMsg = updateMethod.getResponseBodyAsString(); if (statusCode == HttpStatus.SC_OK) { log.info(""); } else { log.error(", " + responseMsg + ", :" + statusCode); throw new Exception(""); } } finally { updateMethod.releaseConnection(); } }
From source file:com.taobao.diamond.client.impl.DefaultDiamondPublisher.java
private void processRemove(String dataId, String group, String content) throws Exception { PostMethod removeMethod = new PostMethod(getRemoveUri()); NameValuePair dataId_value = new NameValuePair("dataId", dataId); NameValuePair group_value = new NameValuePair("group", group); NameValuePair content_value = new NameValuePair("content", content); removeMethod.addRequestHeader(Constants.APPNAME, this.appName); removeMethod.setRequestBody(new NameValuePair[] { dataId_value, group_value, content_value }); this.configureHttpMethod(removeMethod); httpClient.getHostConfiguration().setHost(diamondConfigure.getDomainNameList().get(domainNamePos.get()), diamondConfigure.getPort()); try {/*from w w w . ja v a 2 s . c o m*/ int statusCode = httpClient.executeMethod(removeMethod); String responseMsg = removeMethod.getResponseBodyAsString(); if (statusCode == HttpStatus.SC_OK) { log.info(""); } else { log.error(", " + responseMsg + ", :" + statusCode); throw new Exception(""); } } finally { removeMethod.releaseConnection(); } }
From source file:com.taobao.diamond.client.impl.DefaultDiamondPublisher.java
private void processPublish(String dataId, String group, String content) throws Exception { PostMethod publishMethod = new PostMethod(getPublishUri()); NameValuePair dataId_value = new NameValuePair("dataId", dataId); NameValuePair group_value = new NameValuePair("group", group); NameValuePair content_value = new NameValuePair("content", content); publishMethod.addRequestHeader(Constants.APPNAME, this.appName); publishMethod.setRequestBody(new NameValuePair[] { dataId_value, group_value, content_value }); this.configureHttpMethod(publishMethod); httpClient.getHostConfiguration().setHost(diamondConfigure.getDomainNameList().get(domainNamePos.get()), diamondConfigure.getPort()); try {/*from www .j a v a 2 s. c om*/ int statusCode = httpClient.executeMethod(publishMethod); String responseMsg = publishMethod.getResponseBodyAsString(); if (statusCode == HttpStatus.SC_OK) { log.info(""); } else { log.error(", " + responseMsg + ", :" + statusCode); throw new Exception(", "); } } finally { publishMethod.releaseConnection(); } }
From source file:com.taobao.diamond.client.impl.DefaultDiamondPublisher.java
private void processUpdateAll(String dataId, String group, String content) throws Exception { PostMethod updateMethod = new PostMethod(getUpdateAllUri()); NameValuePair dataId_value = new NameValuePair("dataId", dataId); NameValuePair group_value = new NameValuePair("group", group); NameValuePair content_value = new NameValuePair("content", content); updateMethod.addRequestHeader(Constants.APPNAME, this.appName); updateMethod.setRequestBody(new NameValuePair[] { dataId_value, group_value, content_value }); this.configureHttpMethod(updateMethod); httpClient.getHostConfiguration().setHost(diamondConfigure.getDomainNameList().get(domainNamePos.get()), diamondConfigure.getPort()); try {//from ww w . j ava 2 s.c o m int statusCode = httpClient.executeMethod(updateMethod); String responseMsg = updateMethod.getResponseBodyAsString(); if (statusCode == HttpStatus.SC_OK) { log.info(""); } else { log.error(", " + responseMsg + ", :" + statusCode); throw new Exception(""); } } finally { updateMethod.releaseConnection(); } }