Java Code Examples for org.apache.commons.httpclient.methods.PostMethod

The following are top voted examples for showing how to use org.apache.commons.httpclient.methods.PostMethod. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: iBase4J-Common   File: HttpUtil.java   View source code 8 votes vote down vote up
public static final String httpClientPost(String url, ArrayList<NameValuePair> list) {
    String result = "";
    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(url);
    try {
        NameValuePair[] params = new NameValuePair[list.size()];
        for (int i = 0; i < list.size(); i++) {
            params[i] = list.get(i);
        }
        postMethod.addParameters(params);
        client.executeMethod(postMethod);
        result = postMethod.getResponseBodyAsString();
    } catch (Exception e) {
        logger.error("", e);
    } finally {
        postMethod.releaseConnection();
    }
    return result;
}
 
Example 2
Project: lib-commons-httpclient   File: TestProxy.java   View source code 7 votes vote down vote up
/**
 * Tests POST via authenticating proxy + host auth + connection close 
 */
public void testPostProxyAuthHostAuthConnClose() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");
    
    this.client.getState().setCredentials(AuthScope.ANY, creds);
    this.client.getState().setProxyCredentials(AuthScope.ANY, creds);
    
    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds, "test", false));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
    
    this.server.setRequestHandler(handlerchain);
    
    this.proxy.requireAuthentication(creds, "test", true);

    PostMethod post = new PostMethod("/");
    post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
    try {
        this.client.executeMethod(post);
        assertEquals(HttpStatus.SC_OK, post.getStatusCode());
        assertNotNull(post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }
}
 
Example 3
Project: Hydrograph   File: HydrographServiceClient.java   View source code 7 votes vote down vote up
public void chcekConnectionStatus() throws IOException {

        HttpClient httpClient = new HttpClient();
        //TODO : add connection details while testing only,remove it once done
        String teradatajson = "{\"username\":\"\",\"password\":\"\",\"hostname\":\"\",\"database\":\"\",\"dbtype\":\"\",\"port\":\"\"}";
        PostMethod postMethod = new PostMethod("http://" + HOST_NAME + ":" + PORT + "/getConnectionStatus");

        //postMethod.addParameter("request_parameters", redshiftjson);
        postMethod.addParameter("request_parameters", teradatajson);

        int response = httpClient.executeMethod(postMethod);
        InputStream inputStream = postMethod.getResponseBodyAsStream();

        byte[] buffer = new byte[1024 * 1024 * 5];
        String path = null;
        int length;
        while ((length = inputStream.read(buffer)) > 0) {
            path = new String(buffer);
        }
        System.out.println("Response of service: " + path);
        System.out.println("==================");
    }
 
Example 4
Project: automat   File: HttpUtil.java   View source code 6 votes vote down vote up
public static final String httpClientPost(String url, ArrayList<NameValuePair> list) {
	String result = "";
	HttpClient client = new HttpClient();
	PostMethod postMethod = new PostMethod(url);
	try {
		NameValuePair[] params = new NameValuePair[list.size()];
		for (int i = 0; i < list.size(); i++) {
			params[i] = list.get(i);
		}
		postMethod.addParameters(params);
		client.executeMethod(postMethod);
		result = postMethod.getResponseBodyAsString();
	} catch (Exception e) {
		logger.error(e);
	} finally {
		postMethod.releaseConnection();
	}
	return result;
}
 
Example 5
Project: lib-commons-httpclient   File: TestProxy.java   View source code 6 votes vote down vote up
/**
 * Tests POST via non-authenticating proxy + host auth + connection keep-alive 
 */
public void testPostHostAuthConnKeepAlive() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");
    
    this.client.getState().setCredentials(AuthScope.ANY, creds);
    
    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
    
    this.server.setRequestHandler(handlerchain);
    
    PostMethod post = new PostMethod("/");
    post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
    try {
        this.client.executeMethod(post);
        assertEquals(HttpStatus.SC_OK, post.getStatusCode());
        assertNotNull(post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }
}
 
Example 6
Project: lib-commons-httpclient   File: TestEntityEnclosingMethod.java   View source code 6 votes vote down vote up
public void testEnclosedEntityNegativeLengthHTTP1_0() throws Exception {
    
    String inputstr = "This is a test message";
    byte[] input = inputstr.getBytes("US-ASCII");
    InputStream instream = new ByteArrayInputStream(input);
    
    RequestEntity requestentity = new InputStreamRequestEntity(
            instream, -14); 
    PostMethod method = new PostMethod("/");
    method.setRequestEntity(requestentity);
    method.setContentChunked(false);
    method.getParams().setVersion(HttpVersion.HTTP_1_0);
    this.server.setHttpService(new EchoService());
    try {
        this.client.executeMethod(method);
        fail("ProtocolException should have been thrown");
    } catch (ProtocolException ex) {
        // expected
    } finally {
        method.releaseConnection();
    }
}
 
Example 7
Project: oscm   File: PaypalRequest.java   View source code 6 votes vote down vote up
/**
 * Creates a pay request from the buyer (who is indirectly referenced by the
 * preapproval key) to the seller/receiver.
 * 
 * @param preapprovalKey
 *            The key from a former preapproval request
 * @param amount
 *            amount to be transfered in Euro
 * @return
 * @throws Exception
 */
public PostMethod buildPayRequest(String preapprovalKey, String receiver,
        String amount) throws Exception {
    final Document doc = createBody("PayRequest");
    final Element payReq = doc.getDocumentElement();

    addElement(payReq, "actionType", "PAY");
    addElement(payReq, "preapprovalKey", preapprovalKey);
    addElement(payReq, "senderEmail",
            "[email protected]");

    final Element receiverList = addElement(payReq, "receiverList", null);
    final Element receiverElement = addElement(receiverList, "receiver",
            null);

    addElement(receiverElement, "amount", amount);
    addElement(receiverElement, "email", receiver);
    return createPostMethod(doc, "Pay");
}
 
Example 8
Project: oscm   File: PayServlet.java   View source code 6 votes vote down vote up
/**
 * Sends the request to paypal. Input is preapprovalKey of buyer, email of
 * seller, and amount to be transferred.
 * 
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)
 */
protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    try {
        final PaypalRequest paypalRequest = new PaypalRequest(
                request.getRemoteAddr());
        final PostMethod post = paypalRequest.buildPayRequest(
                request.getParameter("preapprovalKey"),
                request.getParameter("email"),
                request.getParameter("amount"));

        setDefaultAttributes(request, paypalRequest,
                sendPaypalRequest(post));

        request.getRequestDispatcher("/payResponse.jsp").forward(request,
                response);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 9
Project: lib-commons-httpclient   File: TestProxy.java   View source code 6 votes vote down vote up
/**
 * Tests POST via authenticating proxy + host auth + connection keep-alive 
 */
public void testPostProxyAuthHostAuthConnKeepAlive() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");
    
    this.client.getState().setCredentials(AuthScope.ANY, creds);
    this.client.getState().setProxyCredentials(AuthScope.ANY, creds);
    
    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
    
    this.server.setRequestHandler(handlerchain);
    
    this.proxy.requireAuthentication(creds, "test", true);

    PostMethod post = new PostMethod("/");
    post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
    try {
        this.client.executeMethod(post);
        assertEquals(HttpStatus.SC_OK, post.getStatusCode());
        assertNotNull(post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }
}
 
Example 10
Project: dlface   File: DownloadClient.java   View source code 6 votes vote down vote up
/**
 * Help method for log
 *
 * @param method method
 */
protected void toString(HttpMethod method) {
    logger.info("===============HTTP METHOD===============");
    final String path = method.getPath();
    logger.info("path = " + path);
    final Header[] headers = method.getRequestHeaders();
    StringBuilder builder = new StringBuilder();
    for (Header header : headers) {
        if (header != null)
            builder.append(header.toString());
    }
    logger.info("header = \n" + builder.toString().trim());
    if (method instanceof PostMethod) {
        PostMethod postMethod = (PostMethod) method;
        builder = new StringBuilder();
        final NameValuePair[] parameters = postMethod.getParameters();
        for (NameValuePair pair : parameters) {
            builder.append(pair.getName()).append("=").append(pair.getValue()).append("\n");
        }
    }
    logger.info("post parameters: \n" + builder.toString().trim());
    logger.info("query string = " + method.getQueryString());
    logger.info("=========================================");
}
 
Example 11
Project: logistimo-web-service   File: LogiURLFetchService.java   View source code 6 votes vote down vote up
@Override
public HttpResponse post(URL urlObj, byte[] payload, String userName, String password,
                         int timeout) {
  HttpClient client = new HttpClient();
  PostMethod method = new PostMethod(urlObj.toString());
  method.setRequestEntity(new ByteArrayRequestEntity(payload));
  method.setRequestHeader("Content-type", "application/json");
  client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
      new DefaultHttpMethodRetryHandler());
  client.getParams().setSoTimeout(1000 * timeout);
  client.getParams().setConnectionManagerTimeout(1000 * timeout);
  if (userName != null && password != null) {
    setBasicAuthorization(method, userName, password);
  }
  try {
    int response = client.executeMethod(method);
    return new HttpResponse(response, method.getResponseBody());
  } catch (IOException e) {
    throw new RuntimeException("Failed to process post request URL: " + urlObj, e);
  } finally {
    method.releaseConnection();
  }

}
 
Example 12
Project: kaltura-ce-sakai-extension   File: KalturaClientBase.java   View source code 6 votes vote down vote up
private PostMethod createPostMethod(KalturaParams kparams,
		KalturaFiles kfiles, String url) {
	PostMethod method = new PostMethod(url);
       method.setRequestHeader("Accept","text/xml,application/xml,*/*");
       method.setRequestHeader("Accept-Charset","utf-8,ISO-8859-1;q=0.7,*;q=0.5");
       
       if (!kfiles.isEmpty()) {        	
           method = this.getPostMultiPartWithFiles(method, kparams, kfiles);        	
       } else {
           method = this.addParams(method, kparams);            
       }
       
       if (isAcceptGzipEncoding()) {
		method.addRequestHeader(HTTP_HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
	}
       

	// Provide custom retry handler is necessary
	method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
			new DefaultHttpMethodRetryHandler (3, false));
	return method;
}
 
Example 13
Project: lib-commons-httpclient   File: TestEntityEnclosingMethod.java   View source code 6 votes vote down vote up
public void testEnclosedEntityChunkedHTTP1_0() throws Exception {
    String inputstr = "This is a test message";
    byte[] input = inputstr.getBytes("US-ASCII");
    InputStream instream = new ByteArrayInputStream(input);
    
    RequestEntity requestentity = new InputStreamRequestEntity(
            instream, InputStreamRequestEntity.CONTENT_LENGTH_AUTO); 
    PostMethod method = new PostMethod("/");
    method.setRequestEntity(requestentity);
    method.setContentChunked(true);
    method.getParams().setVersion(HttpVersion.HTTP_1_0);
    this.server.setHttpService(new EchoService());
    try {
        this.client.executeMethod(method);
        fail("ProtocolException should have been thrown");
    } catch (ProtocolException ex) {
        // expected
    } finally {
        method.releaseConnection();
    }
}
 
Example 14
Project: iBase4J   File: HttpUtil.java   View source code 6 votes vote down vote up
public static final String httpClientPost(String url, ArrayList<NameValuePair> list) {
	String result = "";
	HttpClient client = new HttpClient();
	PostMethod postMethod = new PostMethod(url);
	try {
		NameValuePair[] params = new NameValuePair[list.size()];
		for (int i = 0; i < list.size(); i++) {
			params[i] = list.get(i);
		}
		postMethod.addParameters(params);
		client.executeMethod(postMethod);
		result = postMethod.getResponseBodyAsString();
	} catch (Exception e) {
		logger.error(e);
	} finally {
		postMethod.releaseConnection();
	}
	return result;
}
 
Example 15
Project: Hydrograph   File: Provider.java   View source code 6 votes vote down vote up
/**
 * 
 * Get post method to get csv debug file
 * 
 * @param jobDetails
 * @param fileSize
 * @return {@link PostMethod}
 * @throws NumberFormatException
 * @throws MalformedURLException
 */
public PostMethod getDebugFileMethod(JobDetails jobDetails,String fileSize) throws NumberFormatException, MalformedURLException {
	
	URL url = new URL(POST_PROTOCOL, getHost(jobDetails), getPortNo(jobDetails), DebugServiceMethods.GET_DEBUG_FILE_PATH);
			
	PostMethod postMethod = new PostMethod(url.toString());
	postMethod.addParameter(DebugServicePostParameters.JOB_ID, jobDetails.getUniqueJobID());
	postMethod.addParameter(DebugServicePostParameters.COMPONENT_ID, jobDetails.getComponentID());
	postMethod.addParameter(DebugServicePostParameters.SOCKET_ID, jobDetails.getComponentSocketID());
	postMethod.addParameter(DebugServicePostParameters.BASE_PATH, jobDetails.getBasepath());
	postMethod.addParameter(DebugServicePostParameters.USER_ID, jobDetails.getUsername());
	postMethod.addParameter(DebugServicePostParameters.DEBUG_SERVICE_PWD, jobDetails.getPassword());
	postMethod.addParameter(DebugServicePostParameters.FILE_SIZE, fileSize);
	postMethod.addParameter(DebugServicePostParameters.HOST_NAME, getHost(jobDetails));
	
	LOGGER.debug("Calling debug service to get csv debug file from url :: "+url);
	
	return postMethod;
}
 
Example 16
Project: lib-commons-httpclient   File: TestEntityEnclosingMethod.java   View source code 6 votes vote down vote up
public void testEnclosedEntityChunked() throws Exception {
    String inputstr = "This is a test message";
    byte[] input = inputstr.getBytes("US-ASCII");
    InputStream instream = new ByteArrayInputStream(input);
    
    RequestEntity requestentity = new InputStreamRequestEntity(
            instream, InputStreamRequestEntity.CONTENT_LENGTH_AUTO); 
    PostMethod method = new PostMethod("/");
    method.setRequestEntity(requestentity);
    method.setContentChunked(true);
    this.server.setHttpService(new EchoService());
    try {
        this.client.executeMethod(method);
        assertEquals(200, method.getStatusCode());
        String body = method.getResponseBodyAsString();
        assertEquals(inputstr, body);
        assertNotNull(method.getRequestHeader("Transfer-Encoding"));
        assertNull(method.getRequestHeader("Content-Length"));
    } finally {
        method.releaseConnection();
    }
}
 
Example 17
Project: Hydrograph   File: HydrographServiceClient.java   View source code 6 votes vote down vote up
public void calltoReadMetastore() throws IOException {

        HttpClient httpClient = new HttpClient();
      //TODO : add connection details while testing only,remove it once done
        String teradatajson = "{\"table\":\"testting2\",\"username\":\"\",\"password\":\"\",\"hostname\":\"\",\"database\":\"\",\"dbtype\":\"\",\"port\":\"\"}";

        PostMethod postMethod = new PostMethod("http://" + HOST_NAME + ":" + PORT + "/readFromMetastore");

        //postMethod.addParameter("request_parameters", redshiftjson);
        postMethod.addParameter("request_parameters", teradatajson);

        int response = httpClient.executeMethod(postMethod);
        InputStream inputStream = postMethod.getResponseBodyAsStream();

        byte[] buffer = new byte[1024 * 1024 * 5];
        String path = null;
        int length;
        while ((length = inputStream.read(buffer)) > 0) {
            path = new String(buffer);
        }
        System.out.println("Response of service: " + path);
        System.out.println("==================");
    }
 
Example 18
Project: lib-commons-httpclient   File: TestProxy.java   View source code 6 votes vote down vote up
/**
 * Tests POST via authenticating proxy
 */
public void testPostAuthProxy() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");
    
    this.client.getState().setProxyCredentials(AuthScope.ANY, creds);
    this.server.setHttpService(new FeedbackService());

    this.proxy.requireAuthentication(creds, "test", true);

    PostMethod post = new PostMethod("/");
    post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
    try {
        this.client.executeMethod(post);
        assertEquals(HttpStatus.SC_OK, post.getStatusCode());
        assertNotNull(post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }
}
 
Example 19
Project: Hydrograph   File: HydrographServiceClient.java   View source code 6 votes vote down vote up
public void calltoReadService() throws IOException {

        HttpClient httpClient = new HttpClient();

        PostMethod postMethod = new PostMethod("http://" + HOST_NAME + ":" + PORT + "/read");
        postMethod.addParameter("jobId", JOB_ID);
        postMethod.addParameter("componentId", COMPONENT_ID);
        postMethod.addParameter("socketId", SOCKET_ID);
        postMethod.addParameter("basePath", BASE_PATH);
        postMethod.addParameter("userId", USER_ID);
        postMethod.addParameter("password", PASSWORD);
        postMethod.addParameter("file_size", FILE_SIZE_TO_READ);
        postMethod.addParameter("host_name", HOST_NAME);

        InputStream inputStream = postMethod.getResponseBodyAsStream();

        byte[] buffer = new byte[1024 * 1024 * 5];
        String path = null;
        int length;
        while ((length = inputStream.read(buffer)) > 0) {
            path = new String(buffer);
        }
        System.out.println("response of service: " + path);
    }
 
Example 20
Project: lib-commons-httpclient   File: TestProxy.java   View source code 6 votes vote down vote up
/**
 * Tests POST via non-authenticating proxy + invalid host auth 
 */
public void testPostHostInvalidAuth() throws Exception {

    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");
    
    this.client.getState().setCredentials(AuthScope.ANY, creds);
    
    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
    
    this.client.getState().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials("testuser", "wrongstuff"));
    
    this.server.setRequestHandler(handlerchain);
    
    PostMethod post = new PostMethod("/");
    post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
    try {
        this.client.executeMethod(post);
        assertEquals(HttpStatus.SC_UNAUTHORIZED, post.getStatusCode());
    } finally {
        post.releaseConnection();
    }
}
 
Example 21
Project: JAVA-   File: HttpUtil.java   View source code 6 votes vote down vote up
public static final String httpClientPost(String url, ArrayList<NameValuePair> list) {
	String result = "";
	HttpClient client = new HttpClient();
	PostMethod postMethod = new PostMethod(url);
	try {
		NameValuePair[] params = new NameValuePair[list.size()];
		for (int i = 0; i < list.size(); i++) {
			params[i] = list.get(i);
		}
		postMethod.addParameters(params);
		client.executeMethod(postMethod);
		result = postMethod.getResponseBodyAsString();
	} catch (Exception e) {
		logger.error(e);
	} finally {
		postMethod.releaseConnection();
	}
	return result;
}
 
Example 22
Project: lib-commons-httpclient   File: TestProxy.java   View source code 6 votes vote down vote up
/**
 * Tests POST via non-authenticating proxy + interactive host auth + connection keep-alive 
 */
public void testPostInteractiveProxyAuthHostAuthConnKeepAlive() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");
    
    this.client.getParams().setParameter(CredentialsProvider.PROVIDER, 
            new GetItWrongThenGetItRight());
    
    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
    
    this.server.setRequestHandler(handlerchain);
    
    this.proxy.requireAuthentication(creds, "test", true);

    PostMethod post = new PostMethod("/");
    post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
    try {
        this.client.executeMethod(post);
        assertEquals(HttpStatus.SC_OK, post.getStatusCode());
        assertNotNull(post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }
}
 
Example 23
Project: sling-org-apache-sling-launchpad-integration-tests   File: SlingPostProcessorTest.java   View source code 6 votes vote down vote up
@Test
public void processorsActive() throws HttpException, IOException {
    final PostMethod post = new PostMethod(testUrl + SlingPostConstants.DEFAULT_CREATE_SUFFIX);
    post.setFollowRedirects(false);
    post.setParameter("DummyModification", "true");

    try {
        T.getHttpClient().executeMethod(post);
        final String content = post.getResponseBodyAsString();
        final int i1 = content.indexOf("source:SlingPostProcessorOne");
        assertTrue("Expecting first processor to be present", i1 > 0);
        final int i2 = content.indexOf("source:SlingPostProcessorTwo");
        assertTrue("Expecting second processor to be present", i2 > 0);
        assertTrue("Expecting service ranking to put processor one first", i1 < i2);
    } finally {
        
        post.releaseConnection();
    }

}
 
Example 24
Project: lib-commons-httpclient   File: TestProxy.java   View source code 6 votes vote down vote up
/**
 * Tests POST via non-authenticating proxy + interactive host auth + connection keep-alive 
 */
public void testPostInteractiveHostAuthConnKeepAlive() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");
    
    this.client.getParams().setParameter(CredentialsProvider.PROVIDER, 
            new GetItWrongThenGetItRight());
    
    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
    
    this.server.setRequestHandler(handlerchain);
    
    PostMethod post = new PostMethod("/");
    post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
    try {
        this.client.executeMethod(post);
        assertEquals(HttpStatus.SC_OK, post.getStatusCode());
        assertNotNull(post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }
}
 
Example 25
Project: sling-org-apache-sling-launchpad-integration-tests   File: PostStatusTest.java   View source code 6 votes vote down vote up
private void simplePost(String url, String statusParam, int expectStatus,
        String expectLocation) throws IOException {

    final PostMethod post = new PostMethod(url);
    post.setFollowRedirects(false);

    if (statusParam != null) {
        post.addParameter(SlingPostConstants.RP_STATUS, statusParam);
    }

    final int status = httpClient.executeMethod(post);
    assertEquals("Unexpected status response", expectStatus, status);

    if (expectLocation != null) {
        String location = post.getResponseHeader("Location").getValue();

        assertNotNull("Expected location header", location);
        assertTrue(location.endsWith(expectLocation));
    }

    post.releaseConnection();
}
 
Example 26
Project: sling-org-apache-sling-launchpad-integration-tests   File: PostToRootTest.java   View source code 6 votes vote down vote up
public void testSetRootProperty() throws Exception {
	String url = HTTP_BASE_URL;
	if(!url.endsWith("/")) {
		url += "/";
	}
       final PostMethod post = new PostMethod(url);
	final String name = getClass().getSimpleName();
	final String value = getClass().getSimpleName() + System.currentTimeMillis();
	post.addParameter(name, value);
	
	final int status = httpClient.executeMethod(post);
	assertEquals(200, status);
	
	final String json = getContent(url + ".json", CONTENT_TYPE_JSON);
	assertJavascript(value, json, "out.print(data." + name + ")");
}
 
Example 27
Project: sling-org-apache-sling-launchpad-integration-tests   File: PostServletOutputContentTypeTest.java   View source code 6 votes vote down vote up
private void runTest(String acceptHeaderValue, boolean useHttpEquiv, String expectedContentType) throws Exception {
    final String info = (useHttpEquiv ? "Using http-equiv parameter" : "Using Accept header") + ": ";
    final String url = HTTP_BASE_URL + MY_TEST_PATH;
    final PostMethod post = new PostMethod(url);
    post.setFollowRedirects(false);
    
    if(acceptHeaderValue != null) {
        if(useHttpEquiv) {
            post.addParameter(":http-equiv-accept", acceptHeaderValue);
        } else {
            post.addRequestHeader("Accept", acceptHeaderValue);
        }
    }
    
    final int status = httpClient.executeMethod(post) / 100;
    assertEquals(info + "Expected status 20x for POST at " + url, 2, status);
    final Header h = post.getResponseHeader("Content-Type");
    assertNotNull(info + "Expected Content-Type header", h);
    final String ct = h.getValue();
    assertTrue(info + "Expected Content-Type '" + expectedContentType + "' for Accept header=" + acceptHeaderValue
            + " but got '" + ct + "'",
            ct.startsWith(expectedContentType));
}
 
Example 28
Project: lib-commons-httpclient   File: TestPostParameterEncoding.java   View source code 6 votes vote down vote up
public void testPostParametersEncoding() throws Exception {
    PostMethod post = new PostMethod();
    post.setRequestBody(new NameValuePair[] { PAIR });
    assertEquals("name=value", getRequestAsString(post.getRequestEntity()));

    post.setRequestBody(new NameValuePair[]{ PAIR, PAIR1, PAIR2 });
    assertEquals("name=value&name1=value1&name2=value2", 
        getRequestAsString(post.getRequestEntity()));

    post.setRequestBody(new NameValuePair[]{ PAIR, PAIR1, PAIR2, new NameValuePair("hasSpace", "a b c d") });
    assertEquals("name=value&name1=value1&name2=value2&hasSpace=a+b+c+d",
        getRequestAsString(post.getRequestEntity()));

    post.setRequestBody(new NameValuePair[]{ new NameValuePair("escaping", ",.-\u00f6\u00e4\[email protected]#*&()=?:;}{[]$") });
    assertEquals("escaping=%2C.-%F6%E4%FC%21%2B%40%23*%26%28%29%3D%3F%3A%3B%7D%7B%5B%5D%24",
        getRequestAsString(post.getRequestEntity()));
    
}
 
Example 29
Project: sling-org-apache-sling-launchpad-integration-tests   File: PostServletDeleteParentTest.java   View source code 6 votes vote down vote up
@Test
public void testDeleteNonExisting() throws Exception {
    final String path = TEST_PATH + "/" + EXISTING_PATH;
    final String testNodeUrl = H.getTestClient().createNode(HttpTest.HTTP_BASE_URL + "/" + path, null);
    assertTrue("Expecting created node path to end with " + path, testNodeUrl.endsWith(path));
    H.assertHttpStatus(testNodeUrl + ".json", 200, "Expecting test node to exist before test");

    // POST :delete to non-existing child node with a path that
    // generates selector + suffix
    final String selectorsPath = TEST_PATH + "/" + deletePath;
    final PostMethod post = new PostMethod(HttpTest.HTTP_BASE_URL + "/" + selectorsPath);
    post.setParameter(":operation",  "delete");
    final int status = H.getHttpClient().executeMethod(post);
    assertEquals("Expecting 403 status for delete operation", 403, status);

    // Test node should still be here
    H.assertHttpStatus(testNodeUrl + ".json", 200, "Expecting test node to exist after test");
}
 
Example 30
Project: sling-org-apache-sling-launchpad-integration-tests   File: RedirectOnLoginErrorTest.java   View source code 6 votes vote down vote up
/**
   * Test SLING-2165.  Login Error should redirect back to the referrer
   * login page.
   *
   * @throws Exception
   */
  public void testRedirectToLoginFormAfterLoginError() throws Exception {
  	//login failure
      List<NameValuePair> params = new ArrayList<NameValuePair>();
      params.add(new NameValuePair("j_username", "___bogus___"));
      params.add(new NameValuePair("j_password", "not_a_real_user"));
      final String loginPageUrl = String.format("%s/system/sling/form/login", HTTP_BASE_URL);
PostMethod post = (PostMethod)assertPostStatus(HTTP_BASE_URL + "/j_security_check",
      		HttpServletResponse.SC_MOVED_TEMPORARILY,
      		params,
      		null,
      		loginPageUrl);

      final Header locationHeader = post.getResponseHeader("Location");
      String location = locationHeader.getValue();
      int queryStrStart = location.indexOf('?');
      if (queryStrStart != -1) {
      	location = location.substring(0, queryStrStart);
      }
      assertEquals("Expected to remain on the form/login page", loginPageUrl, location);
  }
 
Example 31
Project: sling-org-apache-sling-launchpad-integration-tests   File: SLING2085Test.java   View source code 6 votes vote down vote up
public void testRecentRequestsEscape() throws Exception {
    final String basePath = "/" + getClass().getSimpleName() + "/" + Math.random(); 
    final String path = basePath + ".html/%22%3e%3cscript%3ealert(29679)%3c/script%3e";
    
    // POST to create node 
    {
        final PostMethod post = new PostMethod(HTTP_BASE_URL + path);
        post.setFollowRedirects(false);
        final int status = httpClient.executeMethod(post);
        assertEquals(201, status);
    }
    
    // And check that recent requests output does not contain <script>
    {
        final String content = getContent(HTTP_BASE_URL + "/system/console/requests?index=1", CONTENT_TYPE_HTML);
        final String scriptTag = "<script>";
        assertFalse("Content should not contain '" + scriptTag + "'", content.contains(scriptTag));
    }
}
 
Example 32
Project: lib-commons-httpclient   File: TestEntityEnclosingMethod.java   View source code 6 votes vote down vote up
public void testEnclosedEntityAutoLength() throws Exception {
    String inputstr = "This is a test message";
    byte[] input = inputstr.getBytes("US-ASCII");
    InputStream instream = new ByteArrayInputStream(input);
    
    RequestEntity requestentity = new InputStreamRequestEntity(
            instream, InputStreamRequestEntity.CONTENT_LENGTH_AUTO); 
    PostMethod method = new PostMethod("/");
    method.setRequestEntity(requestentity);
    this.server.setHttpService(new EchoService());
    try {
        this.client.executeMethod(method);
        assertEquals(200, method.getStatusCode());
        String body = method.getResponseBodyAsString();
        assertEquals(inputstr, body);
        assertNull(method.getRequestHeader("Transfer-Encoding"));
        assertNotNull(method.getRequestHeader("Content-Length"));
        assertEquals(input.length, Integer.parseInt(
                method.getRequestHeader("Content-Length").getValue()));
    } finally {
        method.releaseConnection();
    }
}
 
Example 33
Project: Spring-Boot-Server   File: HttpUtils.java   View source code 6 votes vote down vote up
public static String getPostResponseHeader(String url,String argJson,List<UHeader> headerList,String headerName){
  	String info = "";
  	try {
   	HttpClient client = new HttpClient();
	PostMethod method = new PostMethod(url);
	client.getParams().setContentCharset("UTF-8");
	if(headerList.size()>0){
		for(int i = 0;i<headerList.size();i++){
			UHeader header = headerList.get(i);
			method.setRequestHeader(header.getHeaderTitle(),header.getHeaderValue());
		}
	}
	method.getParams().setParameter(
			HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
	if(argJson != null && !argJson.trim().equals("")) {
		RequestEntity requestEntity = new StringRequestEntity(argJson,"application/json","UTF-8");
		method.setRequestEntity(requestEntity);
	}
	method.releaseConnection();
	Header h =  method.getResponseHeader(headerName);
	info = h.getValue();
} catch (IOException e) {
	e.printStackTrace();
}
  	return info;
  }
 
Example 34
Project: alfresco-remote-api   File: PublicApiHttpClient.java   View source code 6 votes vote down vote up
public HttpResponse post(final RequestContext rq, final String scope, final int version, final String entityCollectionName, final Object entityId,
            final String relationCollectionName, final Object relationshipEntityId, final String body, String contentType, final Map<String, String> params) throws IOException
{
    RestApiEndpoint endpoint = new RestApiEndpoint(rq.getNetworkId(), scope, version, entityCollectionName, entityId, relationCollectionName,
                relationshipEntityId, params);
    String url = endpoint.getUrl();

    PostMethod req = new PostMethod(url.toString());
    if (body != null)
    {
        if (contentType == null || contentType.isEmpty())
        {
            contentType = "application/json";
        }
        StringRequestEntity requestEntity = new StringRequestEntity(body, contentType, "UTF-8");
        req.setRequestEntity(requestEntity);
    }
    return submitRequest(req, rq);
}
 
Example 35
Project: alfresco-remote-api   File: PublicApiHttpClient.java   View source code 6 votes vote down vote up
public HttpResponse post(final RequestContext rq, final String scope, final int version, final String entityCollectionName, final Object entityId,
                         final String relationCollectionName, final Object relationshipEntityId, final byte[] body, String contentType) throws IOException
{
    RestApiEndpoint endpoint = new RestApiEndpoint(rq.getNetworkId(), scope, version, entityCollectionName, entityId, relationCollectionName,
            relationshipEntityId, null);
    String url = endpoint.getUrl();

    PostMethod req = new PostMethod(url.toString());
    if (body != null)
    {
        if (contentType == null || contentType.isEmpty())
        {
            contentType = "application/octet-stream";
        }
        ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(body, contentType);
        req.setRequestEntity(requestEntity);
    }
    return submitRequest(req, rq);
}
 
Example 36
Project: lib-commons-httpclient   File: TestProxy.java   View source code 6 votes vote down vote up
/**
 * Tests POST via non-authenticating proxy + host auth + connection close 
 */
public void testPostHostAuthConnClose() throws Exception {
    UsernamePasswordCredentials creds = 
        new UsernamePasswordCredentials("testuser", "testpass");
    
    this.client.getState().setCredentials(AuthScope.ANY, creds);
    
    HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain();
    handlerchain.appendHandler(new AuthRequestHandler(creds, "test", false));
    handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService()));
    
    this.server.setRequestHandler(handlerchain);
    
    PostMethod post = new PostMethod("/");
    post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null));
    try {
        this.client.executeMethod(post);
        assertEquals(HttpStatus.SC_OK, post.getStatusCode());
        assertNotNull(post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }
}
 
Example 37
Project: lib-commons-httpclient   File: TestEntityEnclosingMethod.java   View source code 6 votes vote down vote up
public void testEnclosedEntityNegativeLength() throws Exception {
    
    String inputstr = "This is a test message";
    byte[] input = inputstr.getBytes("US-ASCII");
    InputStream instream = new ByteArrayInputStream(input);
    
    RequestEntity requestentity = new InputStreamRequestEntity(
            instream, -14); 
    PostMethod method = new PostMethod("/");
    method.setRequestEntity(requestentity);
    method.setContentChunked(false);
    this.server.setHttpService(new EchoService());
    try {
        this.client.executeMethod(method);
        assertEquals(200, method.getStatusCode());
        String body = method.getResponseBodyAsString();
        assertEquals(inputstr, body);
        assertNotNull(method.getRequestHeader("Transfer-Encoding"));
        assertNull(method.getRequestHeader("Content-Length"));
    } finally {
        method.releaseConnection();
    }
}
 
Example 38
Project: ditb   File: Client.java   View source code 5 votes vote down vote up
/**
 * Send a POST request
 * @param cluster the cluster definition
 * @param path the path or URI
 * @param headers the HTTP headers to include, <tt>Content-Type</tt> must be
 * supplied
 * @param content the content bytes
 * @return a Response object with response detail
 * @throws IOException
 */
public Response post(Cluster cluster, String path, Header[] headers, 
    byte[] content) throws IOException {
  PostMethod method = new PostMethod();
  try {
    method.setRequestEntity(new ByteArrayRequestEntity(content));
    int code = execute(cluster, method, headers, path);
    headers = method.getResponseHeaders();
    content = method.getResponseBody();
    return new Response(code, headers, content);
  } finally {
    method.releaseConnection();
  }
}
 
Example 39
Project: Pluto-Android   File: ApiClient.java   View source code 5 votes vote down vote up
private static void setPostParams(PostMethod postMethod,Map<String,Object> params){
	for (String name : params.keySet()) {
		postMethod.setParameter(name,String.valueOf(params.get(name)));
		//parts[i++] = new StringPart(name, String.valueOf(params.get(name)), UTF_8);
		// System.out.println("post_key==> "+name+"    value==>"+String.valueOf(params.get(name)));
	}
}
 
Example 40
Project: DBus   File: HttpRequest.java   View source code 5 votes vote down vote up
public String doPost(String url, String charset, String jsonObj) {
    String resStr = null;
    HttpClient htpClient = new HttpClient();
    PostMethod postMethod = new PostMethod(url);
    postMethod.getParams().setParameter(
            HttpMethodParams.HTTP_CONTENT_CHARSET, charset);
    try {
        postMethod.setRequestEntity(new StringRequestEntity(jsonObj,
                "application/json", charset));
        int statusCode = htpClient.executeMethod(postMethod);
        if (statusCode != HttpStatus.SC_OK) {
            // post和put不能自动处理转发 301:永久重定向,告诉客户端以后应从新地址访问 302:Moved
            if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                    || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                Header locationHeader = postMethod
                        .getResponseHeader("location");
                String location = null;
                if (locationHeader != null) {
                    location = locationHeader.getValue();
                    log.info("The page was redirected to :" + location);
                } else {
                    log.info("Location field value is null");
                }
            } else {
                log.error("Method failed: " + postMethod.getStatusLine());
            }
            return resStr;
        }
        byte[] responseBody = postMethod.getResponseBody();
        resStr = new String(responseBody, charset);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        postMethod.releaseConnection();
    }
    return resStr;
}