Example usage for org.apache.commons.httpclient.methods PostMethod PostMethod

List of usage examples for org.apache.commons.httpclient.methods PostMethod PostMethod

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods PostMethod PostMethod.

Prototype

public PostMethod() 

Source Link

Usage

From source file:net.sf.antcontrib.net.httpclient.GetMethodTask.java

protected HttpMethodBase createNewMethod() {
    return new PostMethod();
}

From source file:net.formio.servlet.MockServletRequests.java

/**
 * Creates new servlet request that contains given resource as multi part.
 * @param paramName//from   w w  w  .  java2  s. c  o m
 * @param resourceName
 * @return
 */
public static MockHttpServletRequest newRequest(String paramName, String resourceName, String mimeType) {
    try {
        MockHttpServletRequest request = new MockHttpServletRequest();
        // Load resource being uploaded
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        Streams.copy(MockServletRequests.class.getResourceAsStream(resourceName), bos, true);
        byte[] fileContent = bos.toByteArray();

        // Create part & entity from resource
        Part[] parts = new Part[] { new FilePart(paramName, new ByteArrayPartSource(resourceName, fileContent),
                mimeType, (String) null) };
        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts,
                new PostMethod().getParams());

        ByteArrayOutputStream requestContent = new ByteArrayOutputStream();
        multipartRequestEntity.writeRequest(requestContent);
        request.setContent(requestContent.toByteArray());
        // Set content type of request (important, includes MIME boundary string)
        String contentType = multipartRequestEntity.getContentType();
        request.setContentType(contentType);
        request.setMethod("POST");
        return request;
    } catch (IOException ex) {
        throw new RuntimeException(ex.getMessage(), ex);
    }
}

From source file:net.formio.portlet.MockPortletRequests.java

/**
 * Creates new portlet request that contains given resource as multi part.
 * @param paramName/*from  ww w.ja v a 2 s.c o  m*/
 * @param resourceName
 * @return
 */
public static MockMultipartActionRequest newRequest(String paramName, String resourceName, String mimeType) {
    try {
        MockMultipartActionRequest request = new MockMultipartActionRequest();
        // Load resource being uploaded
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        Streams.copy(MockPortletRequests.class.getResourceAsStream(resourceName), bos, true);
        byte[] fileContent = bos.toByteArray();

        // Create part & entity from resource
        Part[] parts = new Part[] { new FilePart(paramName, new ByteArrayPartSource(resourceName, fileContent),
                mimeType, (String) null) };
        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts,
                new PostMethod().getParams());

        ByteArrayOutputStream requestContent = new ByteArrayOutputStream();
        multipartRequestEntity.writeRequest(requestContent);
        request.setContent(requestContent.toByteArray());
        // Set content type of request (important, includes MIME boundary string)
        String contentType = multipartRequestEntity.getContentType();
        request.setContentType(contentType);
        return request;
    } catch (IOException ex) {
        throw new RuntimeException(ex.getMessage(), ex);
    }
}

From source file:net.sf.j2ep.test.PostTest.java

public void beginSendMultipart(WebRequest theRequest) {
    theRequest.setURL("localhost:8080", "/test", "/POST/multipart.jsp", null, null);
    theRequest.addParameter("tmp", "", WebRequest.POST_METHOD);

    try {//from   w ww  .  ja v a  2  s .  c o  m
        PostMethod post = new PostMethod();
        FilePart filePart = new FilePart("theFile", new File("WEB-INF/classes/net/sf/j2ep/test/POSTdata"));
        StringPart stringPart = new StringPart("testParam", "123456");
        Part[] parts = new Part[2];
        parts[0] = stringPart;
        parts[1] = filePart;
        MultipartRequestEntity reqEntitiy = new MultipartRequestEntity(parts, post.getParams());

        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        reqEntitiy.writeRequest(outStream);

        theRequest.setUserData(new ByteArrayInputStream(outStream.toByteArray()));
        theRequest.addHeader("content-type", reqEntitiy.getContentType());
    } catch (FileNotFoundException e) {
        fail("File was not found " + e.getMessage());
    } catch (IOException e) {
        fail("IOException");
        e.printStackTrace();
    }
}

From source file:com.comcast.cats.jenkins.service.AbstractService.java

/**
 * Typical web service client class to get a string representation of the
 * response./*ww w .j a  va  2  s  .c o m*/
 * 
 * @param requestUrl
 *            Relative request URL
 * @param mapperClass
 *            Class to which the response should cast to.
 * @return JAXB deserialized response
 */
protected Object getForObject(final String requestUrl, Class<?> mapperClass, String parameters) {
    Object domainObject = null;
    HttpClient client = new HttpClient();

    try {
        PostMethod request = new PostMethod();
        request.setURI(new URI(getAbsoluteUrl(requestUrl + REQUEST_URL_SUFFIX + parameters), false));
        request.addRequestHeader(CONTENT_TYPE, APPLICATION_XML);
        String apiToken = jenkinsClientProperties.getJenkinsApiToken();
        if (!apiToken.isEmpty()) {
            request.setDoAuthentication(true);
        }
        domainObject = sendRequestToJenkins(mapperClass, domainObject, client, request, apiToken);

    } catch (Exception e) {
        LOGGER.error(e.getMessage());
    }

    return domainObject;
}

From source file:eu.impact_project.iif.t2.client.HelperTest.java

/**
 * Test of parseRequest method, of class Helper.
 *//*from  ww  w . j  a v  a  2  s.  c  o  m*/
@Test
public void testParseRequest() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    URL url = this.getClass().getResource("/prueba.txt");
    File testFile = new File(url.getFile());
    Part[] parts = new Part[] { new StringPart("user", "user"), new FilePart("file_workflow", testFile),
            new FilePart("comon_file", testFile) };

    MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts,
            new PostMethod().getParams());

    ByteArrayOutputStream requestContent = new ByteArrayOutputStream();

    multipartRequestEntity.writeRequest(requestContent);

    final ByteArrayInputStream inputContent = new ByteArrayInputStream(requestContent.toByteArray());

    when(request.getInputStream()).thenReturn(new ServletInputStream() {
        @Override
        public int read() throws IOException {
            return inputContent.read();
        }
    });

    when(request.getContentType()).thenReturn(multipartRequestEntity.getContentType());

    Helper.parseRequest(request);

}

From source file:eu.impact_project.iif.t2.client.WorkflowRunnerTest.java

/**
 * Test of doPost method, of class WorkflowRunner.
 *//*  ww w. ja v a 2  s  .com*/
@Test
public void testDoPost() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    ServletConfig config = mock(ServletConfig.class);
    ServletContext context = mock(ServletContext.class);
    RequestDispatcher dispatcher = mock(RequestDispatcher.class);
    ServletOutputStream stream = mock(ServletOutputStream.class);
    HttpSession session = mock(HttpSession.class);

    when(request.getSession(true)).thenReturn(session);

    ArrayList<Workflow> flowList = new ArrayList<>();
    Workflow flow = new Workflow();
    flow.setStringVersion("Esto es una prueba");
    flow.setWsdls("<wsdl>http://www.ua.es</wsdl>");
    flow.setUrls("http://www.ua.es");

    ArrayList<WorkflowInput> flowInputs = new ArrayList<>();
    WorkflowInput input = new WorkflowInput("pru0Input");
    input.setDepth(1);
    flowInputs.add(input);

    input = new WorkflowInput("pru1Input");
    input.setDepth(0);
    flowInputs.add(input);

    flow.setInputs(flowInputs);

    flowList.add(flow);
    when(session.getAttribute("workflows")).thenReturn(flowList);

    when(config.getServletContext()).thenReturn(context);
    URL url = this.getClass().getResource("/config.properties");
    File testFile = new File(url.getFile());
    when(context.getRealPath("/")).thenReturn(testFile.getParent() + "/");

    Part[] parts = new Part[] { new StringPart("user", "user"), new StringPart("pass", "pass"),
            new StringPart("workflow0pru0Input", "prueba0"), new StringPart("workflow0pru0Input0", "prueba0.0"),
            new StringPart("workflow0pru1Input", "prueba1")

    };

    MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts,
            new PostMethod().getParams());

    ByteArrayOutputStream requestContent = new ByteArrayOutputStream();

    multipartRequestEntity.writeRequest(requestContent);

    final ByteArrayInputStream inputContent = new ByteArrayInputStream(requestContent.toByteArray());

    when(request.getInputStream()).thenReturn(new ServletInputStream() {
        @Override
        public int read() throws IOException {
            return inputContent.read();
        }
    });

    when(request.getContentType()).thenReturn(multipartRequestEntity.getContentType());

    WorkflowRunner runer = new WorkflowRunner();
    try {
        runer.init(config);
        runer.doPost(request, response);

    } catch (ServletException ex) {
        fail("Should not raise exception " + ex.toString());
    } catch (IOException ex) {
        fail("Should not raise exception " + ex.toString());
    } catch (NullPointerException ex) {
        //ok no funciona el server de taverna
    }
}

From source file:fr.openwide.talendalfresco.rest.client.ClientCommandBase.java

/**
 * Can be overriden to tune the default behaviour,
 * check or build parameters.../*www.  ja v a2 s.c o m*/
 * The client should set the params (query string) itself.
 */
public HttpMethodBase createMethod() throws RestClientException {
    // instantiating a new method and configuring it
    HttpMethodBase method;
    switch (this.getMethodType()) {
    case POST:
        //case PUT:
        method = new PostMethod();
        break;
    case GET:
    default:
        method = new GetMethod();
        method.setFollowRedirects(true);
    }
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    //method.setQueryString(params.toArray(new NameValuePair[0])); // done in client
    //method.getParams().setContentCharset(this.restEncoding); // done in client

    // set request entity (allow to fill method body for posts) :
    if (requestEntity != null && method instanceof EntityEnclosingMethod) {
        ((EntityEnclosingMethod) method).setRequestEntity(requestEntity);
    }

    return method;
}

From source file:com.xerox.amazonws.sqs2.MessageQueue.java

/**
 * Sends a message to a specified queue. The message must be between 1 and 256K bytes long.
 *
 * @param msg the message to be sent/*  w ww  .  j a va 2s. c  om*/
 */
public String sendMessage(String msg) throws SQSException {
    Map<String, String> params = new HashMap<String, String>();
    String encodedMsg = enableEncoding ? new String(Base64.encodeBase64(msg.getBytes())) : msg;
    params.put("MessageBody", encodedMsg);
    PostMethod method = new PostMethod();
    try {
        SendMessageResponse response = makeRequest(method, "SendMessage", params, SendMessageResponse.class);
        return response.getSendMessageResult().getMessageId();
    } catch (JAXBException ex) {
        throw new SQSException("Problem parsing returned message.", ex);
    } catch (HttpException ex) {
        throw new SQSException(ex.getMessage(), ex);
    } catch (IOException ex) {
        throw new SQSException(ex.getMessage(), ex);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.xerox.amazonws.sqs.MessageQueue.java

/**
 * Sends a message to a specified queue. The message must be between 1 and 256K bytes long.
 *
 * @param msg the message to be sent//from   w  ww . ja va 2 s . c o  m
 */
public String sendMessage(String msg) throws SQSException {
    Map<String, String> params = new HashMap<String, String>();
    String encodedMsg = enableEncoding ? new String(Base64.encodeBase64(msg.getBytes())) : msg;
    PostMethod method = new PostMethod();
    try {
        method.setRequestEntity(new StringRequestEntity(encodedMsg, "text/plain", null));
        SendMessageResponse response = makeRequest(method, "SendMessage", params, SendMessageResponse.class);
        return response.getMessageId();
    } catch (JAXBException ex) {
        throw new SQSException("Problem parsing returned message.", ex);
    } catch (HttpException ex) {
        throw new SQSException(ex.getMessage(), ex);
    } catch (IOException ex) {
        throw new SQSException(ex.getMessage(), ex);
    } finally {
        method.releaseConnection();
    }
}