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

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

Introduction

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

Prototype

public void setRequestEntity(RequestEntity paramRequestEntity) 

Source Link

Usage

From source file:net.jadler.AbstractJadlerStubbingIntegrationTest.java

@Test
public void havingBody() throws Exception {
    onRequest().havingBodyEqualTo("postbody").havingBody(notNullValue()).havingBody(not(isEmptyOrNullString()))
            .respond().withStatus(201);//from  ww w  .  j a  v a  2  s .  co m

    final PostMethod method = new PostMethod("http://localhost:" + port());
    method.setRequestEntity(new StringRequestEntity("postbody", null, null));

    int status = client.executeMethod(method);
    assertThat(status, is(201));

    method.releaseConnection();
}

From source file:net.jadler.AbstractJadlerStubbingIntegrationTest.java

@Test
public void havingEmptyBody() throws Exception {
    onRequest().havingBodyEqualTo("").havingBody(notNullValue()).havingBody(isEmptyString()).respond()
            .withStatus(201);//from  www.jav  a2 s  .co m

    final PostMethod method = new PostMethod("http://localhost:" + port());
    method.setRequestEntity(new StringRequestEntity("", null, null));

    int status = client.executeMethod(method);
    assertThat(status, is(201));

    method.releaseConnection();
}

From source file:Interface.FramePrincipal.java

private void bt_uplActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_uplActionPerformed

    File diretorio = new File(dir_arq.getText());
    File file = new File(dir_arq.getText() + "/" + nom_arq.getText());

    if (!diretorio.exists()) {
        JOptionPane.showMessageDialog(null, "Informe um diretrio vlido!");
    } else if (!file.exists() || "".equals(nom_arq.getText())) {
        JOptionPane.showMessageDialog(null, "Informe um arquivo vlido!");
    } else {//from   w  w w  .ja  v a2  s. c om
        try {
            //////////////////////////////////////// Validar tamanho de arquivo/////////////////////////////////////////////////               
            RandomAccessFile arquivo = new RandomAccessFile(dir_arq.getText() + "/" + nom_arq.getText(), "r");
            long tamanho = arquivo.length();

            if (tamanho >= 104857600) {
                JOptionPane.showMessageDialog(null, "Arquivo excedeu o tamanho mximo de 100 MB!");
                arquivo.close();
                return;
            }

            //////////////////////////////////////////// Carrega arquivo para o bucket /////////////////////////////////////////
            HttpClient client = new HttpClient();
            client.getParams().setParameter("http.useragent", "Test Client");

            BufferedReader br = null;
            String apikey = "AIzaSyAuKiAdUluAz4IEaOUoXldA8XuwEbty5V8";

            File input = new File(dir_arq.getText() + "/" + nom_arq.getText());

            PostMethod method = new PostMethod("https://www.googleapis.com/upload/storage/v1/b/" + bac.getNome()
                    + "/o?uploadType=media&name=" + nom_arq.getText());
            method.addParameter("uploadType", "media");
            method.addParameter("name", nom_arq.getText());
            method.setRequestEntity(new InputStreamRequestEntity(new FileInputStream(input), input.length()));
            //       method.setRequestHeader("Content-type", "image/png; charset=ISO-8859-1");
            method.setRequestHeader("Content-type", "application/octet-stream");

            //       try{
            int returnCode = client.executeMethod(method);

            if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
                System.err.println("The Post method is not implemented by this URI");
                method.getResponseBodyAsString();
            } else {
                br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
                String readLine;
                while (((readLine = br.readLine()) != null)) {
                    System.err.println(readLine);
                }
                br.close();
            }

        } catch (Exception e) {
            System.err.println(e);

        }
        JOptionPane.showMessageDialog(null, "Arquivo carregado com sucesso!");
    }
}

From source file:net.jadler.AbstractJadlerStubbingIntegrationTest.java

@Test
public void havingUTF8Body() throws Exception {

    onRequest().havingBodyEqualTo(STRING_WITH_DIACRITICS).havingRawBodyEqualTo(UTF_8_REPRESENTATION).respond()
            .withStatus(201);//from  w  ww.  j  ava2  s .c o m

    final PostMethod method = new PostMethod("http://localhost:" + port());
    method.setRequestEntity(
            new StringRequestEntity(STRING_WITH_DIACRITICS, "text/plain", UTF_8_CHARSET.name()));

    int status = client.executeMethod(method);
    assertThat(status, is(201));

    method.releaseConnection();
}

From source file:net.jadler.AbstractJadlerStubbingIntegrationTest.java

@Test
public void havingISOBody() throws Exception {

    onRequest().havingBodyEqualTo(STRING_WITH_DIACRITICS).havingRawBodyEqualTo(ISO_8859_2_REPRESENTATION)
            .respond().withStatus(201);//ww w.  ja  v  a 2 s  .co m

    final PostMethod method = new PostMethod("http://localhost:" + port());
    method.setRequestEntity(
            new StringRequestEntity(STRING_WITH_DIACRITICS, "text/plain", ISO_8859_2_CHARSET.name()));

    int status = client.executeMethod(method);
    assertThat(status, is(201));

    method.releaseConnection();
}

From source file:net.jadler.AbstractJadlerStubbingIntegrationTest.java

@Test
public void respondUsingResponder() throws IOException {
    onRequest().havingMethodEqualTo("POST").respondUsing(new Responder() {

        @Override/*www.  ja v  a  2  s  .  co m*/
        public StubResponse nextResponse(final Request request) {

            return StubResponse.builder().status(201)
                    .header("Content-Type", "text/plain; charset=" + request.getEncoding().name())
                    .body(request.getBodyAsBytes()).build();
        }
    });

    final PostMethod method = new PostMethod("http://localhost:" + port());
    method.setRequestEntity(new StringRequestEntity(STRING_WITH_DIACRITICS, UTF_8_TYPE, null));
    final int status = client.executeMethod(method);
    assertThat(status, is(201));
    assertThat(method.getResponseBodyAsString(), is(STRING_WITH_DIACRITICS));

    method.releaseConnection();
}

From source file:com.zimbra.qa.unittest.TestJaxb.java

private Element sendReqExpectingFail(String requestBody, String requestCommand, int expectedRespCode)
        throws HttpException, IOException, ServiceException {
    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod(TestUtil.getSoapUrl() + requestCommand);
    post.setRequestEntity(new StringRequestEntity(requestBody, "application/soap+xml", "UTF-8"));
    int respCode = HttpClientUtil.executeMethod(client, post);
    Assert.assertEquals(expectedRespCode, respCode);
    return W3cDomUtil.parseXML(post.getResponseBodyAsStream());
}

From source file:com.zimbra.qa.unittest.TestJaxb.java

private Object sendReq(String requestBody, String requestCommand)
        throws HttpException, IOException, ServiceException {
    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod(TestUtil.getSoapUrl() + requestCommand);
    post.setRequestEntity(new StringRequestEntity(requestBody, "application/soap+xml", "UTF-8"));
    int respCode = HttpClientUtil.executeMethod(client, post);
    Assert.assertEquals(200, respCode);//from  w w  w .ja v a2 s  .c  o  m
    Element envelope = W3cDomUtil.parseXML(post.getResponseBodyAsStream());
    SoapProtocol proto = SoapProtocol.determineProtocol(envelope);
    Element doc = proto.getBodyElement(envelope);
    return JaxbUtil.elementToJaxb(doc);
}

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;//from w w w  .  ja v  a2s.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:net.jadler.AbstractJadlerStubbingIntegrationTest.java

@Test
public void havingParameterPOST() throws Exception {
    final String body = "p1=p1v1&p2=p2v1&p2=p2v2&p3=&p4&url%20encoded=url%20encoded";

    onRequest().havingParameter("p1").havingParameter("p1", hasSize(1))
            .havingParameter("p1", everyItem(not(isEmptyOrNullString())))
            .havingParameter("p1", contains("p1v1")).havingParameterEqualTo("p1", "p1v1").havingParameter("p2")
            .havingParameter("p2", hasSize(3)).havingParameter("p2", hasItems("p2v1", "p2v2", "p2v3"))
            .havingParameterEqualTo("p2", "p2v1").havingParameterEqualTo("p2", "p2v2")
            .havingParameterEqualTo("p2", "p2v3").havingParameters("p1", "p2").havingParameter("p3")
            .havingParameter("p3", contains("")).havingParameterEqualTo("p3", "").havingParameter("p4")
            .havingParameter("p4", contains("")).havingParameterEqualTo("p4", "")
            .havingParameter("p5", nullValue()).havingParameter("url%20encoded", contains("url%20encoded"))
            .havingBodyEqualTo(body).respond().withStatus(201);

    final PostMethod method = new PostMethod("http://localhost:" + port() + "?p2=p2v3");
    method.setRequestEntity(new StringRequestEntity(body, "application/x-www-form-urlencoded", "UTF-8"));

    int status = client.executeMethod(method);
    assertThat(status, is(201));/*from  w  w w  .  jav  a 2s  .c  om*/

    method.releaseConnection();
}