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.stormpath.spring.boot.examples.filter.ReCaptchaFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    if (!(req instanceof HttpServletRequest)
            || !("POST".equalsIgnoreCase(((HttpServletRequest) req).getMethod()))) {
        chain.doFilter(req, res);//w  w  w.ja va  2s.co  m
        return;
    }

    PostMethod method = new PostMethod(RECAPTCHA_URL);
    method.addParameter("secret", RECAPTCHA_SECRET);
    method.addParameter("response", req.getParameter(RECAPTCHA_RESPONSE_PARAM));
    method.addParameter("remoteip", req.getRemoteAddr());

    HttpClient client = new HttpClient();
    client.executeMethod(method);
    BufferedReader br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
    String readLine;
    StringBuffer response = new StringBuffer();
    while (((readLine = br.readLine()) != null)) {
        response.append(readLine);
    }

    JSONObject jsonObject = new JSONObject(response.toString());
    boolean success = jsonObject.getBoolean("success");

    if (success) {
        chain.doFilter(req, res);
    } else {
        ((HttpServletResponse) res).sendError(HttpStatus.BAD_REQUEST.value(), "Bad ReCaptcha");
    }
}

From source file:com.avego.cloudinary.Cloudinary.java

/**
 * Encodes the provided bytes in Base 64, parcels it up in a signed JSON Object and fires it at Cloudinary.
 * @param bytes//from   ww  w  .  j av  a 2  s . c  om
 * @param mimeType
 * @return
 * @throws CloudinaryException
 */
public String postPhotoToCloudinary(byte[] bytes, String mimeType) throws CloudinaryException {

    PostMethod post = new PostMethod(this.cloudinaryRepository.getUploadUrl());

    long currentTime = new Date().getTime();

    String signature = generateSignature(currentTime, null);

    String base64RepresentationOfImage = Base64.encodeBytes(bytes);
    StringBuilder payload = buildCreationPayload(base64RepresentationOfImage, currentTime, signature, mimeType);

    LOGGER.trace("Sending JSON payload to Cloudinary: " + payload);

    String response = postJsonToCloudinary(post, payload);

    return extractPublicIdFromJson(response);
}

From source file:fr.aliasource.webmail.server.invitation.GetInvitationInfoProxyImpl.java

@SuppressWarnings("unchecked")
@Override// www .  j  av a  2  s.  com
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    IAccount ac = (IAccount) req.getSession().getAttribute("account");

    if (ac == null) {
        GWT.log("Account not found in session", null);
        resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    PostMethod pm = new PostMethod(backendUrl);
    if (req.getQueryString() != null) {
        pm.setQueryString(req.getQueryString());
    }
    Map<String, String[]> params = req.getParameterMap();
    for (String p : params.keySet()) {
        String[] val = params.get(p);
        pm.setParameter(p, val[0]);
    }

    synchronized (hc) {
        try {
            int ret = hc.executeMethod(pm);
            if (ret != HttpStatus.SC_OK) {
                log("method failed:\n" + pm.getStatusLine() + "\n" + pm.getResponseBodyAsString());
                resp.setStatus(ret);
            } else {
                InputStream is = pm.getResponseBodyAsStream();
                transfer(is, resp.getOutputStream(), false);
            }

        } catch (Exception e) {
            log("error occured on call proxyfication", e);
        } finally {
            pm.releaseConnection();
        }
    }
}

From source file:net.sourceforge.jwbf.actions.mw.login.PostLogin.java

/**
 * //from   w ww.  j  a v a2s .co  m
 * @param username the
 * @param pw password
 */
public PostLogin(final String username, final String pw) {

    NameValuePair userid = new NameValuePair("lgname", username);
    NameValuePair password = new NameValuePair("lgpassword", pw);

    PostMethod pm = new PostMethod("/api.php?action=login&format=xml");

    pm.setRequestBody(new NameValuePair[] { userid, password });
    pm.getParams().setContentCharset(MediaWikiBot.CHARSET);
    msgs.add(pm);

}

From source file:com.ifeng.vdn.ip.repository.service.impl.AliBatchIPAddressChecker.java

@Override
public List<AliIPBean> check(List<String> ips) {

    List<AliIPBean> list = new ArrayList<AliIPBean>();

    AliIPBean ipaddress = null;//  w  w  w  . ja va  2s  .  co  m
    String url = "http://ip.taobao.com/service/getIpInfo2.php";

    for (String ip : ips) {

        // Create an instance of HttpClient.
        HttpClient clinet = new HttpClient();

        // Create a method instance.
        PostMethod postMethod = new PostMethod(url);

        // Execute the method.
        try {
            postMethod.setParameter("ip", ip);
            int resultCode = clinet.executeMethod(postMethod);

            if (resultCode == HttpStatus.SC_OK) {
                // Read the response body.
                InputStream responseBody = postMethod.getResponseBodyAsStream();

                ObjectMapper mapper = new ObjectMapper();
                ipaddress = mapper.readValue(responseBody, AliIPBean.class);

                log.info(responseBody.toString());

                list.add(ipaddress);
            } else {
                list.add(new AliIPBean());
                log.error("Method failedd: [{}] , IP: [{}]", postMethod.getStatusCode(), ip);
            }

        } catch (JsonParseException | JsonMappingException | HttpException e) {
            list.add(new AliIPBean());
            log.error(e.getMessage(), e);
        } catch (IOException e) {
            list.add(new AliIPBean());
            log.error(e.getMessage(), e);
        }
    }
    return list;
}

From source file:fr.aliasource.webmail.server.proxy.client.http.AbstractClientMethod.java

protected InputStream executeStream(Map<String, String> parameters) {
    InputStream is = null;/*from ww w . j a  v a 2s  .  c om*/
    PostMethod pm = new PostMethod(url);
    pm.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
    for (String p : parameters.keySet()) {
        pm.setParameter(p, parameters.get(p));
    }
    int ret = 0;
    synchronized (hc) {
        try {
            ret = hc.executeMethod(pm);
            if (ret == HttpStatus.SC_NOT_MODIFIED) {
                logger.info("backend wants us to use cached data");
            } else if (ret != HttpStatus.SC_OK) {
                logger.error("method failed:\n" + pm.getStatusLine() + "\n" + pm.getResponseBodyAsString());
            } else {
                is = pm.getResponseBodyAsStream();
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                transfer(is, out, true);
                return new ByteArrayInputStream(out.toByteArray());
            }
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
        } finally {
            pm.releaseConnection();
        }
    }
    return is;
}

From source file:com.predic8.membrane.integration.Http10Test.java

@Test
public void testPost() throws Exception {

    HttpClient client = new HttpClient();
    client.getParams().setParameter(HttpProtocolParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_0);

    PostMethod post = new PostMethod("http://localhost:3000/axis2/services/BLZService");
    InputStream stream = this.getClass().getResourceAsStream("/getBank.xml");

    InputStreamRequestEntity entity = new InputStreamRequestEntity(stream);
    post.setRequestEntity(entity);/*from w  ww. ja  v a2  s. c o m*/
    post.setRequestHeader(Header.CONTENT_TYPE, MimeType.TEXT_XML_UTF8);
    post.setRequestHeader(Header.SOAP_ACTION, "\"\"");
    int status = client.executeMethod(post);
    assertEquals(200, status);
    assertEquals("HTTP/1.1", post.getStatusLine().getHttpVersion());

    String response = post.getResponseBodyAsString();
    assertNotNull(response);
    assertTrue(response.length() > 0);
}

From source file:net.morphbank.webclient.PostXML.java

public void post(String strURL, String strXMLFilename) throws Exception {
    File input = new File(strXMLFilename);
    // Prepare HTTP post
    PostMethod post = new PostMethod(strURL);
    // Request content will be retrieved directly
    // from the input stream Part[] parts = {
    Part[] parts = { new FilePart("uploadFile", strXMLFilename, input) };
    RequestEntity entity = new MultipartRequestEntity(parts, post.getParams());
    // RequestEntity entity = new FileRequestEntity(input,
    // "text/xml;charset=utf-8");
    post.setRequestEntity(entity);//from   w ww . j  ava  2s. co  m
    // Get HTTP client
    HttpClient httpclient = new HttpClient();
    // Execute request
    try {
        System.out.println("Trying post");
        int result = httpclient.executeMethod(post);
        // Display status code
        System.out.println("Response status code: " + result);
        // Display response
        System.out.println("Response body: ");
        InputStream response = post.getResponseBodyAsStream();
        //int j = response.read(); System.out.write(j);
        for (int i = response.read(); i != -1; i = response.read()) {
            System.out.write(i);
        }
        //System.out.flush();
    } finally {
        // Release current connection to the connection pool once you are
        // done
        post.releaseConnection();
    }
}

From source file:be.fedict.trust.service.util.ClockDriftUtil.java

public static Date executeTSP(ClockDriftConfigEntity clockDriftConfig, NetworkConfig networkConfig)
        throws IOException, TSPException {

    LOG.debug("clock drift detection: " + clockDriftConfig.toString());

    TimeStampRequestGenerator requestGen = new TimeStampRequestGenerator();

    TimeStampRequest request = requestGen.generate(TSPAlgorithms.SHA1, new byte[20], BigInteger.valueOf(100));
    byte[] requestData = request.getEncoded();

    HttpClient httpClient = new HttpClient();

    if (null != networkConfig) {
        httpClient.getHostConfiguration().setProxy(networkConfig.getProxyHost(), networkConfig.getProxyPort());
    }/*w  w  w. ja  v a  2s  .  c o m*/

    PostMethod postMethod = new PostMethod(clockDriftConfig.getServer());
    postMethod.setRequestEntity(new ByteArrayRequestEntity(requestData, "application/timestamp-query"));

    int statusCode = httpClient.executeMethod(postMethod);
    if (statusCode != HttpStatus.SC_OK) {
        throw new TSPException("Error contacting TSP server " + clockDriftConfig.getServer());
    }

    TimeStampResponse tspResponse = new TimeStampResponse(postMethod.getResponseBodyAsStream());
    postMethod.releaseConnection();

    return tspResponse.getTimeStampToken().getTimeStampInfo().getGenTime();
}

From source file:com.owncloud.android.files.StreamMediaFileOperation.java

protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result;//from  w ww  .  j a v  a2 s  . co  m
    PostMethod postMethod = null;

    try {
        postMethod = new PostMethod(client.getBaseUri() + STREAM_MEDIA_URL + JSON_FORMAT);
        postMethod.setParameter("fileId", fileID);

        // remote request
        postMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);

        int status = client.executeMethod(postMethod, SYNC_READ_TIMEOUT, SYNC_CONNECTION_TIMEOUT);

        if (status == HttpStatus.SC_OK) {
            String response = postMethod.getResponseBodyAsString();

            // Parse the response
            JSONObject respJSON = new JSONObject(response);
            String url = respJSON.getJSONObject(NODE_OCS).getJSONObject(NODE_DATA).getString(NODE_URL);

            result = new RemoteOperationResult(true, postMethod);
            ArrayList<Object> urlArray = new ArrayList<>();
            urlArray.add(url);
            result.setData(urlArray);
        } else {
            result = new RemoteOperationResult(false, postMethod);
            client.exhaustResponse(postMethod.getResponseBodyAsStream());
        }
    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Get stream url for file with id " + fileID + " failed: " + result.getLogMessage(),
                result.getException());
    } finally {
        if (postMethod != null) {
            postMethod.releaseConnection();
        }
    }
    return result;
}