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:mercury.UploadController.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
        try {//from  ww w  .j av  a  2  s  .  co m
            List items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (!item.isFormField()) {
                    String targetUrl = Config.getConfigProperty(ConfigurationEnum.DIGITAL_MEDIA);
                    if (StringUtils.isBlank(targetUrl)) {
                        targetUrl = request.getRequestURL().toString();
                        targetUrl = targetUrl.substring(0, targetUrl.lastIndexOf('/'));
                    }
                    targetUrl += "/DigitalMediaController";
                    PostMethod filePost = new PostMethod(targetUrl);
                    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
                    UploadPartSource src = new UploadPartSource(item.getName(), item.getSize(),
                            item.getInputStream());
                    Part[] parts = new Part[1];
                    parts[0] = new FilePart(item.getName(), src, item.getContentType(), null);
                    filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
                    HttpClient client = new HttpClient();
                    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
                    int status = client.executeMethod(filePost);
                    if (status == HttpStatus.SC_OK) {
                        String data = filePost.getResponseBodyAsString();
                        JSONObject json = new JSONObject(data);
                        if (json.has("id")) {
                            JSONObject responseJson = new JSONObject();
                            responseJson.put("success", true);
                            responseJson.put("id", json.getString("id"));
                            responseJson.put("uri", targetUrl + "?id=" + json.getString("id"));
                            response.getWriter().write(responseJson.toString());
                        }
                    }
                    filePost.releaseConnection();
                    return;
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (JSONException je) {
            je.printStackTrace();
        }
    }
    response.getWriter().write("{success: false}");
}

From source file:lucee.commons.net.http.httpclient3.HTTPEngine3Impl.java

public static HTTPResponse post(URL url, String username, String password, long timeout, int maxRedirect,
        String charset, String useragent, ProxyData proxy, Header[] headers, Map<String, String> params)
        throws IOException {
    return _invoke(new PostMethod(url.toExternalForm()), url, username, password, timeout, maxRedirect, charset,
            useragent, proxy, headers, params, null);
}

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

private void testPost(boolean useExpect100Continue) throws Exception {
    HttpClient client = new HttpClient();
    if (useExpect100Continue)
        initExpect100ContinueWithFastFail(client);
    PostMethod post = new PostMethod("http://localhost:4000/axis2/services/BLZService");
    InputStream stream = this.getClass().getResourceAsStream("/getBank.xml");

    InputStreamRequestEntity entity = new InputStreamRequestEntity(stream);
    post.setRequestEntity(entity);/*from w  w w. ja  v a 2  s.c o  m*/
    post.setRequestHeader(Header.CONTENT_TYPE, MimeType.TEXT_XML_UTF8);
    post.setRequestHeader(Header.SOAP_ACTION, "");

    int status = client.executeMethod(post); // also see comment on initExpect100ContinueWithFastFail()
    assertEquals(200, status);
    assertNotNull(post.getResponseBodyAsString());
    assertFalse(isNullOrEmpty(post.getResponseBodyAsString()));
    //System.out.println(post.getResponseBodyAsString());
}

From source file:arena.httpclient.commons.JakartaCommonsHttpClient.java

public HttpResponse get() throws IOException {
    NameValuePair params[] = new NameValuePair[0];
    if (this.requestParameters != null) {
        List<NameValuePair> paramList = new ArrayList<NameValuePair>();
        for (String key : this.requestParameters.keySet()) {
            String[] multipleValues = this.requestParameters.get(key);
            for (String value : multipleValues) {
                paramList.add(new NameValuePair(key, value));
            }//  w  w w .  j av a  2s . com
        }
        params = paramList.toArray(new NameValuePair[paramList.size()]);
    }

    HttpMethod method = null;
    if (this.isPost) {
        method = new PostMethod(this.url);
        if (this.encoding != null) {
            method.getParams().setContentCharset(this.encoding);
        }
        ((PostMethod) method).setRequestBody(params);
    } else {
        String url = this.url;
        for (int n = 0; n < params.length; n++) {
            url = URLUtils.addParamToURL(url, params[n].getName(), params[n].getValue(), this.encoding, false);
        }
        method = new GetMethod(url);
        method.setFollowRedirects(true);
        if (this.encoding != null) {
            method.getParams().setContentCharset(this.encoding);
        }
    }

    HttpClient client = new HttpClient(this.manager);
    if (this.connectTimeout != null) {
        client.getHttpConnectionManager().getParams().setConnectionTimeout(this.connectTimeout.intValue());
    }
    if (this.readTimeout != null) {
        client.getHttpConnectionManager().getParams().setSoTimeout(this.readTimeout.intValue());
    }
    client.setState(this.state);
    try {
        int statusCode = client.executeMethod(method);
        return new HttpResponse(getResponseBytes(method), statusCode,
                buildHeaderMap(method.getResponseHeaders()));
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:com.temenos.interaction.commands.webhook.WebhookCommand.java

/**
 * @precondition url has been supplied//from  www.j  a v a 2  s  . c o  m
 * @postcondition Result.Success if {@link InteractionContext#getResource()} is successfully POSTed to url
 */
@SuppressWarnings("unchecked")
@Override
public Result execute(InteractionContext ctx) {
    if (url != null && url.length() > 0) {
        Map<String, Object> properties = null;
        try {
            OEntity oentity = ((EntityResource<OEntity>) ctx.getResource()).getEntity();
            properties = transform(oentity);
        } catch (ClassCastException cce) {
            if (LOGGER.isWarnEnabled()) {
                LOGGER.warn("Failed to cast the OEntity.", cce);
            }
            Entity entity = ((EntityResource<Entity>) ctx.getResource()).getEntity();
            properties = transform(entity);
        }
        String formData = getFormData(properties);
        try {
            LOGGER.info("POST " + url + " [" + formData + "]");
            HttpClient client = new HttpClient();
            PostMethod postMethod = new PostMethod(url);
            postMethod.setRequestEntity(
                    new StringRequestEntity(formData, "application/x-www-form-urlencoded", "UTF-8"));
            client.executeMethod(postMethod);
            LOGGER.info("Status [" + postMethod.getStatusCode() + "]");
        } catch (Exception e) {
            LOGGER.error("Error POST " + url + " [" + formData + "]", e);
            return Result.FAILURE;
        }
    } else {
        LOGGER.warn("DISABLED - no url supplied");
    }
    return Result.SUCCESS;
}

From source file:eu.learnpad.core.impl.ca.XwikiBridgeInterfaceRestResource.java

@Override
public String putValidateCollaborativeContent(CollaborativeContentAnalysis contentFile) throws LpRestException {
    HttpClient httpClient = this.getAnonymousClient();
    String uri = String.format("%s/learnpad/ca/bridge/validatecollaborativecontent", this.restPrefix);
    PostMethod postMethod = new PostMethod(uri);

    postMethod.addRequestHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML);
    try {//from   w w w.  j a  va  2s  .  c om
        StringWriter contentWriter = new StringWriter();
        JAXBContext context = JAXBContext.newInstance(CollaborativeContentAnalysis.class);
        Marshaller marshaller = context.createMarshaller();
        marshaller.marshal(contentFile, contentWriter);

        RequestEntity entity = new StringRequestEntity(contentWriter.toString(), MediaType.APPLICATION_XML,
                null);
        postMethod.setRequestEntity(entity);
    } catch (JAXBException | UnsupportedEncodingException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause());
    }

    try {
        httpClient.executeMethod(postMethod);
        return postMethod.getResponseBodyAsString();
    } catch (IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause());
    }
}

From source file:com.cloud.cluster.ClusterServiceServletImpl.java

@Override
public boolean ping(String callingPeer) throws RemoteException {
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Ping at " + _serviceUrl);
    }//from  w w w .ja v  a  2 s .c  o  m

    HttpClient client = getHttpClient();
    PostMethod method = new PostMethod(_serviceUrl);

    method.addParameter("method", Integer.toString(RemoteMethodConstants.METHOD_PING));
    method.addParameter("callingPeer", callingPeer);

    String returnVal = executePostMethod(client, method);
    if ("true".equalsIgnoreCase(returnVal)) {
        return true;
    }
    return false;
}

From source file:com.alternatecomputing.jschnizzle.renderer.YUMLRenderer.java

public BufferedImage render(Diagram diagram) {
    String script = diagram.getScript();
    if (script == null) {
        throw new RendererException("no script defined.");
    }/*from w w  w .  java2  s  .c  om*/
    StringTokenizer st = new StringTokenizer(script.trim(), "\n");
    StringBuilder buffer = new StringBuilder();
    while (st.hasMoreTokens()) {
        String token = st.nextToken();
        if (token.startsWith("#")) {
            continue; // skip over comments
        }
        buffer.append(token.trim());
        if (st.hasMoreTokens()) {
            buffer.append(", ");
        }
    }
    buffer.append(".svg");

    String style = diagram.getStyle().getValue();
    String baseURL = getBaseURL();
    try {
        HttpClient client = new HttpClient();
        String proxyHost = System.getProperty("http.proxyHost");
        String proxyPort = System.getProperty("http.proxyPort");
        if (StringUtils.isNotBlank(proxyHost) && StringUtils.isNotBlank(proxyPort)) {
            client.getHostConfiguration().setProxy(proxyHost, Integer.parseInt(proxyPort));
        }

        String postURI = baseURL + "diagram/" + style + "/" + diagram.getType().getUrlModifier() + "/";
        LOGGER.debug(postURI);
        PostMethod postMethod = new PostMethod(postURI);
        postMethod.addParameter("dsl_text", buffer.toString());
        client.executeMethod(postMethod);
        String svgResourceName = postMethod.getResponseBodyAsString();
        postMethod.releaseConnection();
        LOGGER.debug(svgResourceName);

        String getURI = baseURL + svgResourceName;
        LOGGER.debug(getURI);
        GetMethod getMethod = new GetMethod(getURI);
        client.executeMethod(getMethod);
        String svgContents = getMethod.getResponseBodyAsString();
        getMethod.releaseConnection();
        LOGGER.debug(svgContents);

        diagram.setEncodedImage(svgContents);
        TranscoderInput input = new TranscoderInput(new ByteArrayInputStream(svgContents.getBytes()));
        BufferedImageTranscoder imageTranscoder = new BufferedImageTranscoder();
        imageTranscoder.transcode(input, null);

        return imageTranscoder.getBufferedImage();
    } catch (MalformedURLException e) {
        throw new RendererException(e);
    } catch (IOException e) {
        throw new RendererException(e);
    } catch (TranscoderException e) {
        throw new RendererException(e);
    }
}

From source file:com.comcast.cats.service.util.HttpClientUtil.java

public static synchronized Object postForObject(String uri, Map<String, String> paramMap) {
    Object responseObject = new Object();

    HttpMethod httpMethod = new PostMethod(uri);

    if ((null != paramMap) && (!paramMap.isEmpty())) {
        httpMethod.setQueryString(getNameValuePair(paramMap));
    }// w  w  w  . j av  a 2s .  com

    Yaml yaml = new Yaml();

    HttpClient client = new HttpClient();
    InputStream responseStream = null;
    Reader inputStreamReader = null;

    try {
        int responseCode = client.executeMethod(httpMethod);

        if (HttpStatus.SC_OK != responseCode) {
            logger.error("[ REQUEST  ] " + httpMethod.getURI().toString());
            logger.error("[ METHOD   ] " + httpMethod.getName());
            logger.error("[ STATUS   ] " + responseCode);
        } else {
            logger.trace("[ REQUEST  ] " + httpMethod.getURI().toString());
            logger.trace("[ METHOD   ] " + httpMethod.getName());
            logger.trace("[ STATUS   ] " + responseCode);
        }

        responseStream = httpMethod.getResponseBodyAsStream();
        inputStreamReader = new InputStreamReader(responseStream, VideoRecorderServiceConstants.UTF);
        responseObject = yaml.load(inputStreamReader);
    } catch (IOException ioException) {
        ioException.printStackTrace();
    } finally {
        cleanUp(inputStreamReader, responseStream, httpMethod);
    }

    return responseObject;
}

From source file:com.compomics.mslims.util.mascot.MascotWebConnector.MascotAuthenticatedConnection.java

/**
 * create a post method with parameters for logging out of the mascot server
 * @return the logout post method/*from  w  ww.j a v  a  2 s  . c  om*/
 * @throws java.lang.IllegalArgumentException
 */
private PostMethod logoutMethod() {

    PostMethod authpost = new PostMethod("/mascot/cgi/login.pl");
    // Prepare login parameters
    NameValuePair[] parameters = { new NameValuePair("action", "logout"),
            new NameValuePair("onerrdisplay", "nothing") };

    authpost.setRequestBody(parameters);

    return authpost;
}