List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestBody
public void setRequestBody(NameValuePair[] paramArrayOfNameValuePair) throws IllegalArgumentException
From source file:org.josso.test.support.TckTestSupport.java
/** * Simplified doPost method// w w w .j a v a 2s . c o m */ protected PostMethod doPost(String url, NameValuePair... params) throws IOException { PostMethod postMethod = new PostMethod(url); postMethod.setRequestBody(params); this.getClient().executeMethod(postMethod); return postMethod; }
From source file:org.josso.test.support.TckTestSupport.java
protected PostMethod doPost(String url, String referer, NameValuePair... params) throws IOException { PostMethod postMethod = new PostMethod(url); postMethod.setRequestBody(params); postMethod.addRequestHeader("REFERER", referer); this.getClient().executeMethod(postMethod); return postMethod; }
From source file:org.kchine.r.server.http.RHttpProxy.java
public static Object invoke(String url, String sessionId, String servantName, String methodName, Class<?>[] methodSignature, Object[] methodParameters, HttpClient httpClient) throws TunnelingException { if (System.getProperty("proxy_host") != null && !System.getProperty("proxy_host").equals("")) { httpClient.getHostConfiguration().setProxy(System.getProperty("proxy_host"), Integer.decode(System.getProperty("proxy_port"))); }//from w w w . j av a2 s .c om PostMethod postPush = null; try { Object result = null; try { postPush = new PostMethod(url + "?method=invoke"); NameValuePair[] data = { new NameValuePair("servantname", PoolUtils.objectToHex(servantName)), new NameValuePair("methodname", PoolUtils.objectToHex(methodName)), new NameValuePair("methodsignature", PoolUtils.objectToHex(methodSignature)), new NameValuePair("methodparameters", PoolUtils.objectToHex(methodParameters)) }; postPush.setRequestBody(data); if (sessionId != null && !sessionId.equals("")) { postPush.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); postPush.setRequestHeader("Cookie", "JSESSIONID=" + sessionId); } httpClient.executeMethod(postPush); result = new ObjectInputStream(postPush.getResponseBodyAsStream()).readObject(); } catch (ConnectException e) { throw new ConnectionFailedException(); } catch (Exception e) { throw new TunnelingException("Client Side", e); } if (result != null && result instanceof TunnelingException) { new Exception().printStackTrace(); throw (TunnelingException) result; } return result; } finally { if (postPush != null) { postPush.releaseConnection(); } } }
From source file:org.manalang.monkeygrease.utils.HttpClient.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String url = request.getParameter("u"); String method = request.getParameter("m"); String params = request.getParameter("p"); InputStream is = null;/*from w w w .ja v a2s .c om*/ if (url == null || url == "") return; if (method != null && method.toLowerCase().equals("post")) { // Create a method instance. PostMethod postMethod = new PostMethod(url); // If params avail, set post data if (params != null && params != "") { String[] paramArray = params.split("&"); NameValuePair[] postData = new NameValuePair[paramArray.length]; for (int i = 0; i < paramArray.length; i++) { String[] nameVal = paramArray[i].split("="); String name = nameVal[0]; String value = nameVal[1]; postData[i] = new NameValuePair(name, value); } postMethod.setRequestBody(postData); } // Provide custom retry handler is necessary postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(2, false)); try { // Execute the method. int statusCode = client.executeMethod(postMethod); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + postMethod.getStatusLine()); } // Read the response body. is = postMethod.getResponseBodyAsStream(); Header[] headers = postMethod.getResponseHeaders(); for (int i = 0; i < headers.length; i++) { Header header = headers[i]; response.setHeader(header.getName(), header.getValue()); } PrintWriter out = response.getWriter(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); String line; while ((line = in.readLine()) != null) { out.println(line); } out.close(); } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // Release the connection. postMethod.releaseConnection(); } } else { if (params != null) { if (url.indexOf("?") == -1) { url = url + "?" + params; } else { url = url + "&" + params; } } // Create a method instance. GetMethod getMethod = new GetMethod(url); // Provide custom retry handler is necessary getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(2, false)); try { // Execute the method. int statusCode = client.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + getMethod.getStatusLine()); } // Read the response body. is = getMethod.getResponseBodyAsStream(); Header[] headers = getMethod.getResponseHeaders(); for (int i = 0; i < headers.length; i++) { Header header = headers[i]; response.setHeader(header.getName(), header.getValue()); } PrintWriter out = response.getWriter(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); String line; while ((line = in.readLine()) != null) { out.println(line); } out.close(); // Deal with the response. // Use caution: ensure correct character encoding and is not // binary data } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // Release the connection. getMethod.releaseConnection(); } } }
From source file:org.mitre.mat.engineclient.MATCgiClient.java
protected JsonNode postHTTP(ArrayList<NameValuePair> pArrayList, HashMap<String, String> data) throws MATEngineClientException { // Serialize the document, send it to HTTP, deserialize. if (data != null) { int mapsize = data.size(); Iterator keyValuePairs1 = data.entrySet().iterator(); for (int i = 0; i < mapsize; i++) { Map.Entry entry = (Map.Entry) keyValuePairs1.next(); Object key = entry.getKey(); Object value = entry.getValue(); pArrayList.add(new NameValuePair((String) key, (String) value)); }/*w ww.ja v a 2 s. c o m*/ } NameValuePair[] pArray = (NameValuePair[]) pArrayList.toArray(new NameValuePair[1]); HttpClientParams params = new HttpClientParams(); params.setContentCharset("utf-8"); HttpClient client = new HttpClient(params); PostMethod method = new PostMethod(url); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false)); method.setRequestBody(pArray); String resString = null; try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { throw new MATEngineClientException("HTTP method failed: " + method.getStatusLine()); } BufferedReader b = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), "utf-8")); StringBuffer buf = new StringBuffer(); int READ_LEN = 2048; char[] cbuf = new char[READ_LEN]; while (true) { int chars = b.read(cbuf, 0, READ_LEN); if (chars < 0) { break; } // You may not read READ_LEN chars, but // that doesn't mean you're done. buf.append(cbuf, 0, chars); } resString = new String(buf); } catch (HttpException e) { throw new MATEngineClientException("Fatal protocol violation: " + e.getMessage()); } catch (IOException e) { throw new MATEngineClientException("Fatal transport error: " + e.getMessage()); } finally { // Release the connection. method.releaseConnection(); } JsonNode responseObj = null; JsonFactory jsonFact = new JsonFactory(); JsonNode jsonValues; JsonParser parser; try { parser = jsonFact.createJsonParser(new StringReader(resString)); return new ObjectMapper().readTree(parser); } catch (org.codehaus.jackson.JsonParseException ex) { Logger.getLogger(MATCgiClient.class.getName()).log(Level.SEVERE, null, ex); throw new MATEngineClientException("Couldn't digest the following string as JSON: " + resString); } catch (IOException ex) { Logger.getLogger(MATCgiClient.class.getName()).log(Level.SEVERE, null, ex); throw new MATEngineClientException("Couldn't interpret response document: " + ex.getMessage()); } }
From source file:org.openadaptor.auxil.connector.http.HttpWriteConnector.java
/** * @see IWriteConnector#deliver(Object[]) * ToDo: handling of the response/*from w w w.j a va 2s . co m*/ * ToDo: javadoc comments */ public Object deliver(Object[] data) { log.info("HTTP write connector, delivering data.."); Object result = new Object[data.length]; PostMethod postMethod = null; for (int i = 0; i < data.length; i++) { NameValuePair[] nameValuePairs = { new NameValuePair(RESPONSE_KEY, data[i].toString()) }; postMethod = new PostMethod(url); postMethod.setRequestBody(nameValuePairs); try { /* Execute the method and check the status */ int statusCode = client.executeMethod(postMethod); if (statusCode != HttpStatus.SC_OK) { log.error("Method failed: " + postMethod.getStatusLine()); return result; } // /* Handle response */ // InputStream in = postMethod.getResponseBodyAsStream(); // } catch (IOException e) { log.error("Error while reading response from HTTP POST", e); } finally { postMethod.releaseConnection(); } } return result; }
From source file:org.openamf.test.RemotingTester.java
public static AMFMessage sendMessage(String gateway, AMFMessage requestMessage) throws IOException, HttpException { ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream(); DataOutputStream outputStream = new DataOutputStream(baOutputStream); AMFSerializer serializer = new AMFSerializer(outputStream); serializer.serializeMessage(requestMessage); PostMethod post = new PostMethod(gateway); post.setRequestBody(new ByteArrayInputStream(baOutputStream.toByteArray())); post.setRequestContentLength(baOutputStream.size()); post.setRequestHeader("Content-type", "application/x-amf"); HttpClient httpclient = new HttpClient(); int result = httpclient.executeMethod(post); DataInputStream inputStream = new DataInputStream(new ByteArrayInputStream(post.getResponseBody())); AMFDeserializer deserializer = new AMFDeserializer(inputStream); AMFMessage resposeMessage = deserializer.getAMFMessage(); // Release current connection to the connection pool once you are done post.releaseConnection();// w w w . java 2 s .c o m return resposeMessage; }
From source file:org.openanzo.client.BinaryStoreClient.java
private void authenticate() throws AnzoException { try {/*from w ww.ja v a 2s. c o m*/ URL aURL = new URL(authentication_url); httpclient.getHostConfiguration().setHost(aURL.getHost(), aURL.getPort(), aURL.getProtocol()); PostMethod authpost = new PostMethod(aURL.getPath()); NameValuePair formUserid = new NameValuePair( EncryptedTokenAuthenticatorConstants.USERNAME_PARAMETER_NAME, anzoClient.clientDatasource.getServiceUser()); NameValuePair formPassword = new NameValuePair( EncryptedTokenAuthenticatorConstants.PASSWORD_PARAMETER_NAME, anzoClient.clientDatasource.getServicePassword()); authpost.setRequestBody(new NameValuePair[] { formUserid, formPassword }); authpost.addRequestHeader("X-Requested-With", "XMLHttpRequest"); authpost.setDoAuthentication(false); httpclient.executeMethod(authpost); if (authpost.getStatusCode() == HttpStatus.SC_FORBIDDEN) { throw new AnzoException(ExceptionConstants.SERVER.BAD_USER_PASSWORD); } authpost.releaseConnection(); CookieSpec cookiespec = CookiePolicy.getDefaultSpec(); Cookie[] logoncookies = cookiespec.match(aURL.getHost(), aURL.getPort() == -1 ? aURL.getDefaultPort() : aURL.getPort(), "/", false, httpclient.getState().getCookies()); boolean authenticated = false; for (int i = 0; i < logoncookies.length; i++) { if (logoncookies[i].getName().equals(EncryptedTokenAuthenticatorConstants.ANZO_TOKEN_COOKIE_NAME)) authenticated = true; } if (!authenticated) throw new AnzoException(ExceptionConstants.SERVER.BAD_USER_PASSWORD); } catch (IOException e) { throw new AnzoException(ExceptionConstants.BINARYSTORECLIENT.BINARYSTORECLIENT_ERROR, e); } }
From source file:org.openanzo.test.TestEncryptedTokenAuthorizationBlocksServletAccess.java
/** * An authenticate request should not invoke the protected servlet. It should be handled only by the authenticator in both successful and invalid * authentication cases.//from ww w . j a v a 2 s. c o m * * @throws Exception */ public void testSuccessfulAuthenticateRequestDoesNotReachServlet() throws Exception { resetServletCounter(); Pair<String, String> userInfo = getDefaultUserAndPassword(); // Send a authentication request that we expect to succeed. HttpClient client = new HttpClient(); PostMethod authpost = new PostMethod( getControlServletURI() + EncryptedTokenAuthenticatorConstants.LOGIN_URI_SUFFIX); NameValuePair formUserid = new NameValuePair(EncryptedTokenAuthenticatorConstants.USERNAME_PARAMETER_NAME, userInfo.first); NameValuePair formPassword = new NameValuePair(EncryptedTokenAuthenticatorConstants.PASSWORD_PARAMETER_NAME, userInfo.second); authpost.setRequestBody(new NameValuePair[] { formUserid, formPassword }); authpost.addRequestHeader("X-Requested-With", "XMLHttpRequest"); authpost.setDoAuthentication(false); client.executeMethod(authpost); int statusCode = authpost.getStatusCode(); assertEquals("Invalid status code. Status text: " + authpost.getStatusText(), HttpStatus.SC_OK, statusCode); authpost.releaseConnection(); Cookie[] logoncookies = client.getState().getCookies(); boolean authenticated = false; for (int i = 0; i < logoncookies.length; i++) { if (logoncookies[i].getName().equals(EncryptedTokenAuthenticatorConstants.ANZO_TOKEN_COOKIE_NAME)) authenticated = true; } assertTrue("Expect a successful authentication.", authenticated); // Get the value of the counter (via a non-protected path) to make sure it stayed at zero, which would indicate the // servlet wasn't touched by the authenticate request. GetMethod request = new GetMethod( getControlServletURI() + ControlServlet.OPERATION_URI_SUFFIX_COUNTER_READ); request.addRequestHeader("X-Requested-With", "XMLHttpRequest"); client.executeMethod(request); statusCode = request.getStatusCode(); assertEquals("Invalid status code. Status text: " + request.getStatusText(), HttpStatus.SC_OK, statusCode); assertEquals("0", request.getResponseBodyAsString()); }
From source file:org.openanzo.test.TestEncryptedTokenAuthorizationBlocksServletAccess.java
/** * An authenticate request should not invoke the protected servlet. It should be handled only by the authenticator in both successful and invalid * authentication cases./*from ww w. j a va 2s .c o m*/ * * @throws Exception */ public void testFailedAuthenticateRequestDoesNotReachServlet() throws Exception { resetServletCounter(); Pair<String, String> userInfo = getDefaultUserAndPassword(); // Send a authentication request that we expect to fail. HttpClient client = new HttpClient(); PostMethod authpost = new PostMethod( getControlServletURI() + EncryptedTokenAuthenticatorConstants.LOGIN_URI_SUFFIX); NameValuePair formUserid = new NameValuePair(EncryptedTokenAuthenticatorConstants.USERNAME_PARAMETER_NAME, userInfo.first); NameValuePair formPassword = new NameValuePair(EncryptedTokenAuthenticatorConstants.PASSWORD_PARAMETER_NAME, "anIncorrectPassword"); authpost.setRequestBody(new NameValuePair[] { formUserid, formPassword }); authpost.addRequestHeader("X-Requested-With", "XMLHttpRequest"); authpost.setDoAuthentication(false); client.executeMethod(authpost); int statusCode = authpost.getStatusCode(); assertEquals("Invalid status code. Status text: " + authpost.getStatusText(), HttpStatus.SC_FORBIDDEN, statusCode); authpost.releaseConnection(); Cookie[] logoncookies = client.getState().getCookies(); boolean authenticated = false; for (int i = 0; i < logoncookies.length; i++) { if (logoncookies[i].getName().equals(EncryptedTokenAuthenticatorConstants.ANZO_TOKEN_COOKIE_NAME)) authenticated = true; } assertFalse("Expect a failed authentication.", authenticated); // Get the value of the counter (via a non-protected path) to make sure it stayed at zero, which would indicate the // servlet wasn't touched by the authenticate request. GetMethod request = new GetMethod( getControlServletURI() + ControlServlet.OPERATION_URI_SUFFIX_COUNTER_READ); request.addRequestHeader("X-Requested-With", "XMLHttpRequest"); client.executeMethod(request); statusCode = request.getStatusCode(); assertEquals("Invalid status code. Status text: " + request.getStatusText(), HttpStatus.SC_OK, statusCode); assertEquals("0", request.getResponseBodyAsString()); }