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(String paramString) 

Source Link

Usage

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

private String sendReq(String userId, String authToken, int expectedCode, boolean useGetInfoReq,
        boolean byAccountId) throws HttpException, IOException {
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(
            TestUtil.getSoapUrl() + (useGetInfoReq ? "GetInfoRequest" : "NoOpRequest"));
    method.setRequestEntity(/*from w  w w  . j  a v  a 2s  .c  o m*/
            new StringRequestEntity(useGetInfoReq ? getInfoRequest(userId, authToken, byAccountId)
                    : getNoOpRequest(userId, authToken, byAccountId), "application/soap+xml", "UTF-8"));
    int respCode = HttpClientUtil.executeMethod(client, method);
    Assert.assertEquals(expectedCode, respCode);
    return method.getResponseBodyAsString();
}

From source file:eu.seaclouds.platform.planner.optimizerTest.service.OptimizerServiceOpenShiftTest.java

@Test(enabled = TestConstants.EnabledTestOpenShift) //check also if the class is enabled
public void testPresenceSolutionBlind() {

    log.info("=== TEST for SOLUTION GENERATION of BLIND optimizer service DEPLOYED IN OPENSHIFT STARTED ===");

    String url = BASE_URL + "optimize";

    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(url);

    method.addParameter("aam", appModel);
    method.addParameter("offers", suitableCloudOffer);
    method.addParameter("optmethod", SearchMethodName.BLINDSEARCH.toString());

    executeAndCheck(client, method, SearchMethodName.BLINDSEARCH.toString());

    log.info("=== TEST for SOLUTION GENERATION of BLIND optimizer service DEPLOYED IN OPENSHIFT FINISEHD ===");

}

From source file:de.extra.client.plugins.outputplugin.transport.ExtraTransportHttp.java

/**
 * ExtrasTransportHttp is an implementation of IExtraTransport and provides
 * Communication via http(s) protocol./*from  w  ww.  ja  v  a  2 s  .c  o m*/
 * 
 * @see de.extra.client.transport.IExtraTransport#senden(java.lang.String)
 */
@Override
public InputStream senden(final InputStream extraRequest) throws ExtraTransportException {

    if (client != null) {

        // Init response
        InputStream extraResponse = null;

        // Build url String and create post request
        PostMethod method = new PostMethod(requestURL);

        try {

            RequestEntity entity = new InputStreamRequestEntity(extraRequest);
            method.setRequestEntity(entity);

            // Execute the method - send it
            int statusCode = client.executeMethod(method);

            // Something goes wrong
            if (statusCode != HttpStatus.SC_OK) {
                throw new ExtraTransportException(
                        "Versand von Request fehlgeschlagen: " + method.getStatusLine());
            } else {

                // Read the response body and save it

                extraResponse = method.getResponseBodyAsStream();
            }

        } catch (HttpException e) {
            throw new ExtraTransportException("Schwere Protokollverletzung: " + e.getMessage(), e);
        } catch (IOException e) {
            throw new ExtraTransportException("Schwerer Transportfehler: " + e.getMessage(), e);
        } finally {

            // Release the connection.
            method.releaseConnection();
        }
        return extraResponse;
    } else {
        throw new ExtraTransportException("Http Client nicht initialisiert!");
    }
}

From source file:com.zb.app.biz.service.WeixinTest.java

public boolean sendMessage(String fakeid, String content) {
    if (isLogin) {
        PostMethod post = new PostMethod(sendUrl);
        post.setRequestHeader("Cookie", this.cookiestr);
        post.setRequestHeader("Host", "mp.weixin.qq.com");
        post.setRequestHeader("Referer",
                "https://mp.weixin.qq.com/cgi-bin/singlesendpage?t=message/send&action=index&token=" + token
                        + "&tofakeid=" + fakeid + "&lang=zh_CN");
        post.setRequestHeader("Content-Type", "text/html;charset=UTF-8");
        post.addParameter(new NameValuePair("type", "1"));
        post.addParameter(new NameValuePair("content", content));
        post.addParameter(new NameValuePair("error", "false"));
        post.addParameter(new NameValuePair("imgcode", ""));
        post.addParameter(new NameValuePair("tofakeid", "681435581"));
        post.addParameter(new NameValuePair("token", token));
        post.addParameter(new NameValuePair("ajax", "1"));
        try {//from   w  ww. ja v a 2s .c o  m
            int code = httpClient.executeMethod(post);
            if (HttpStatus.SC_OK == code) {
                System.out.println(post.getResponseBodyAsString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        login();
        sendMessage(fakeid, content);
    }
    return false;
}

From source file:hydrograph.server.service.HydrographServiceClient.java

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;/* w ww .  jav  a  2 s  . c o  m*/
    int length;
    while ((length = inputStream.read(buffer)) > 0) {
        path = new String(buffer);
    }
    System.out.println("Response of service: " + path);
    System.out.println("==================");
}

From source file:fr.openwide.talendalfresco.rest.client.importer.RestImportFileTest.java

public void testSingleFileImport() {
    // create client and configure it
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);

    // instantiating a new method and configuring it
    PostMethod method = new PostMethod(restCommandUrlPrefix + "import");
    // Provide custom retry handler is necessary (?)
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    NameValuePair[] params = new NameValuePair[] { new NameValuePair("path", "/app:company_home"),
            new NameValuePair("ticket", ticket) };
    method.setQueryString(params);/*ww w.  j  a v a  2s  .  co m*/

    try {
        //method.setRequestBody(new NameValuePair[] {
        //      new NameValuePair("path", "/app:company_home") });
        FileInputStream acpXmlIs = new FileInputStream(SAMPLE_SINGLE_FILE_PATH);
        InputStreamRequestEntity entity = new InputStreamRequestEntity(acpXmlIs);
        //InputStreamRequestEntity entity = new InputStreamRequestEntity(acpXmlIs, "text/xml; charset=ISO-8859-1");
        method.setRequestEntity(entity);
    } catch (IOException ioex) {
        fail("ACP XML file not found " + ioex.getMessage());
    }

    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody();
        System.out.println(new String(responseBody)); // TODO rm

        HashSet<String> defaultElementSet = new HashSet<String>(
                Arrays.asList(new String[] { RestConstants.TAG_COMMAND, RestConstants.TAG_CODE,
                        RestConstants.TAG_CONTENT, RestConstants.TAG_ERROR, RestConstants.TAG_MESSAGE }));
        HashMap<String, String> elementValueMap = new HashMap<String, String>(6);

        try {
            XMLEventReader xmlReader = XmlHelper.getXMLInputFactory()
                    .createXMLEventReader(new ByteArrayInputStream(responseBody));
            StringBuffer singleLevelTextBuf = null;
            while (xmlReader.hasNext()) {
                XMLEvent event = xmlReader.nextEvent();
                switch (event.getEventType()) {
                case XMLEvent.CHARACTERS:
                case XMLEvent.CDATA:
                    if (singleLevelTextBuf != null) {
                        singleLevelTextBuf.append(event.asCharacters().getData());
                    } // else element not meaningful
                    break;
                case XMLEvent.START_ELEMENT:
                    StartElement startElement = event.asStartElement();
                    String elementName = startElement.getName().getLocalPart();
                    if (defaultElementSet.contains(elementName)
                            // TODO another command specific level
                            || "ticket".equals(elementName)) {
                        // reinit buffer at start of meaningful elements
                        singleLevelTextBuf = new StringBuffer();
                    } else {
                        singleLevelTextBuf = null; // not useful
                    }
                    break;
                case XMLEvent.END_ELEMENT:
                    if (singleLevelTextBuf == null) {
                        break; // element not meaningful
                    }

                    // TODO or merely put it in the map since the element has been tested at start
                    EndElement endElement = event.asEndElement();
                    elementName = endElement.getName().getLocalPart();
                    if (defaultElementSet.contains(elementName)) {
                        String value = singleLevelTextBuf.toString();
                        elementValueMap.put(elementName, value);
                        // TODO test if it is code and it is not OK, break to error handling
                    }
                    // TODO another command specific level
                    else if ("ticket".equals(elementName)) {
                        ticket = singleLevelTextBuf.toString();
                    }
                    // singleLevelTextBuf = new StringBuffer(); // no ! in start
                    break;
                }
            }
        } catch (XMLStreamException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Throwable t) {
            // TODO Auto-generated catch block
            t.printStackTrace();
            //throw t;
        }

        String code = elementValueMap.get(RestConstants.TAG_CODE);
        assertTrue(RestConstants.CODE_OK.equals(code));
        System.out.println("got ticket " + ticket);

    } catch (HttpException e) {
        // TODO
        e.printStackTrace();
    } catch (IOException e) {
        // TODO
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:net.duckling.ddl.web.api.APIMobileVersionController.java

private void formatDupdate(HttpServletResponse resp, String type) {
    HttpClient dClient = new HttpClient();
    PostMethod method = new PostMethod(getDupdateUrl());
    method.setParameter("type", type);
    method.setParameter("projectName", getProjectName());
    try {/*from www  .  ja v a  2 s.c o m*/
        dClient.executeMethod(method);
        String response = method.getResponseBodyAsString();
        Map<String, Object> map = dealJsonResult(response);
        JSONObject obj = new JSONObject();
        obj.put("updateMessage", map.get("descreption"));
        obj.put("result", map.get("success"));
        obj.put("version", map.get("version"));
        String url = (String) map.get("downloadUrl");
        if (StringUtils.isEmpty(url)) {
            url = "http://www.escience.cn/apks/ddl-latest.apk";
        }
        obj.put("downloadUrl", url);
        obj.put("isForce", map.get("forcedUpdate"));
        JsonUtil.writeJSONObject(resp, obj);
    } catch (HttpException e) {
        LOG.error("", e);
    } catch (IOException e) {
        LOG.error("", e);
    } catch (ParseException e) {
        LOG.error("", e);
    }

}

From source file:com.calclab.emite.xtesting.services.HttpConnector.java

private Runnable createSendAction(final String httpBase, final String xml, final ConnectorCallback callback) {
    return new Runnable() {
        public void run() {
            final String id = HttpConnectorID.getNext();
            debug("Connector [{0}] send: {1}", id, xml);
            final HttpClientParams params = new HttpClientParams();
            params.setConnectionManagerTimeout(10000);
            final HttpClient client = new HttpClient(params);
            int status = 0;
            String response = null;
            final PostMethod post = new PostMethod(httpBase);

            try {
                post.setRequestEntity(new StringRequestEntity(xml, "text/xml", "utf-8"));
                System.out.println("SENDING: " + xml);
                status = client.executeMethod(post);
                response = post.getResponseBodyAsString();
            } catch (final Exception e) {
                callback.onError(xml, e);
                e.printStackTrace();//www  .ja va 2 s .  c  o  m
            } finally {
                post.releaseConnection();
            }

            receiveService.execute(createResponseAction(xml, callback, id, status, response));
        }
    };
}

From source file:cn.newtouch.util.HttpClientUtil.java

/**
 * /*from  w w w.  j  a v  a 2 s.c om*/
 * List ?
 * 
 * @since 2011-11-25
 * @param url
 * @param params
 *            ?
 * @return
 */
public static String post(String url, List<LabelValue> params) {
    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(url);

    try {
        client.getParams().setContentCharset(ENCODING_UTF);// ?

        for (LabelValue temp : params) {
            postMethod.addParameter(new NameValuePair(temp.getValue(), temp.getValue()));// username?values
        }

        int tmpStatusCode = client.executeMethod(postMethod);

        // ?
        if (tmpStatusCode == HttpStatus.SC_OK) {
            return postMethod.getResponseBodyAsString();

        } else {
            return null;
        }
    } catch (Exception e) {
        System.err.println(e);
    } finally {
        postMethod.releaseConnection();
    }
    return null;
}

From source file:com.zimbra.cs.client.soap.LmcSendMsgRequest.java

public String postAttachment(String uploadURL, LmcSession session, File f, String domain, // cookie domain e.g. ".example.zimbra.com"
        int msTimeout) throws LmcSoapClientException, IOException {
    String aid = null;/*from   www  .j  a  v a 2  s  .  c  o  m*/

    // set the cookie.
    if (session == null)
        System.err.println(System.currentTimeMillis() + " " + Thread.currentThread()
                + " LmcSendMsgRequest.postAttachment session=null");

    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    PostMethod post = new PostMethod(uploadURL);
    ZAuthToken zat = session.getAuthToken();
    Map<String, String> cookieMap = zat.cookieMap(false);
    if (cookieMap != null) {
        HttpState initialState = new HttpState();
        for (Map.Entry<String, String> ck : cookieMap.entrySet()) {
            Cookie cookie = new Cookie(domain, ck.getKey(), ck.getValue(), "/", -1, false);
            initialState.addCookie(cookie);
        }
        client.setState(initialState);
        client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    }
    post.getParams().setSoTimeout(msTimeout);
    int statusCode = -1;
    try {
        String contentType = URLConnection.getFileNameMap().getContentTypeFor(f.getName());
        Part[] parts = { new FilePart(f.getName(), f, contentType, "UTF-8") };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
        statusCode = HttpClientUtil.executeMethod(client, post);

        // parse the response
        if (statusCode == 200) {
            // paw through the returned HTML and get the attachment id
            String response = post.getResponseBodyAsString();
            //System.out.println("response is\n" + response);
            int lastQuote = response.lastIndexOf("'");
            int firstQuote = response.indexOf("','") + 3;
            if (lastQuote == -1 || firstQuote == -1)
                throw new LmcSoapClientException("Attachment post failed, unexpected response: " + response);
            aid = response.substring(firstQuote, lastQuote);
        } else {
            throw new LmcSoapClientException("Attachment post failed, status=" + statusCode);
        }
    } catch (IOException e) {
        System.err.println("Attachment post failed");
        e.printStackTrace();
        throw e;
    } finally {
        post.releaseConnection();
    }

    return aid;
}