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:ccc.migration.FileUploader.java

private ResourceSummary uploadFile(final String hostPath, final UUID parentId, final String fileName,
        final String originalTitle, final String originalDescription, final Date originalLastUpdate,
        final PartSource ps, final String contentType, final String charset, final boolean publish)
        throws IOException {

    final PostMethod filePost = new PostMethod(hostPath);

    try {/*from  w  ww . j  a va2 s .  c  om*/
        LOG.debug("Migrating file: " + fileName);
        final String name = ResourceName.escape(fileName).toString();

        final String title = (null != originalTitle) ? originalTitle : fileName;

        final String description = (null != originalDescription) ? originalDescription : "";

        final String lastUpdate;
        if (originalLastUpdate == null) {
            lastUpdate = "" + new Date().getTime();
        } else {
            lastUpdate = "" + originalLastUpdate.getTime();
        }

        final FilePart fp = new FilePart("file", ps);
        fp.setContentType(contentType);
        fp.setCharSet(charset);
        final Part[] parts = { new StringPart("fileName", name), new StringPart("title", title),
                new StringPart("description", description), new StringPart("lastUpdate", lastUpdate),
                new StringPart("path", parentId.toString()), new StringPart("publish", String.valueOf(publish)),
                fp };
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

        _client.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECTION_TIMEOUT);

        final int status = _client.executeMethod(filePost);
        if (status == HttpStatus.SC_OK) {
            final String entity = filePost.getResponseBodyAsString();
            LOG.debug("Upload complete, response=" + entity);

            return new S11nProvider<ResourceSummary>().readFrom(ResourceSummary.class, ResourceSummary.class,
                    null, MediaType.valueOf(filePost.getResponseHeader("Content-Type").getValue()), null,
                    filePost.getResponseBodyAsStream());
        }

        throw RestExceptionMapper.fromResponse(filePost.getResponseBodyAsString());

    } finally {
        filePost.releaseConnection();
    }
}

From source file:com.noelios.restlet.ext.httpclient.HttpMethodCall.java

/**
 * Constructor./*from   w  ww. j  a v  a2s .  co  m*/
 * 
 * @param helper
 *            The parent HTTP client helper.
 * @param method
 *            The method name.
 * @param requestUri
 *            The request URI.
 * @param hasEntity
 *            Indicates if the call will have an entity to send to the
 *            server.
 * @throws IOException
 */
public HttpMethodCall(HttpClientHelper helper, final String method, String requestUri, boolean hasEntity)
        throws IOException {
    super(helper, method, requestUri);
    this.clientHelper = helper;

    if (requestUri.startsWith("http")) {
        if (method.equalsIgnoreCase(Method.GET.getName())) {
            this.httpMethod = new GetMethod(requestUri);
        } else if (method.equalsIgnoreCase(Method.POST.getName())) {
            this.httpMethod = new PostMethod(requestUri);
        } else if (method.equalsIgnoreCase(Method.PUT.getName())) {
            this.httpMethod = new PutMethod(requestUri);
        } else if (method.equalsIgnoreCase(Method.HEAD.getName())) {
            this.httpMethod = new HeadMethod(requestUri);
        } else if (method.equalsIgnoreCase(Method.DELETE.getName())) {
            this.httpMethod = new DeleteMethod(requestUri);
        } else if (method.equalsIgnoreCase(Method.CONNECT.getName())) {
            final HostConfiguration host = new HostConfiguration();
            host.setHost(new URI(requestUri, false));
            this.httpMethod = new ConnectMethod(host);
        } else if (method.equalsIgnoreCase(Method.OPTIONS.getName())) {
            this.httpMethod = new OptionsMethod(requestUri);
        } else if (method.equalsIgnoreCase(Method.TRACE.getName())) {
            this.httpMethod = new TraceMethod(requestUri);
        } else {
            this.httpMethod = new EntityEnclosingMethod(requestUri) {
                @Override
                public String getName() {
                    return method;
                }
            };
        }

        this.httpMethod.setFollowRedirects(this.clientHelper.isFollowRedirects());
        this.httpMethod.setDoAuthentication(false);

        if (this.clientHelper.getRetryHandler() != null) {
            try {
                this.httpMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                        Engine.loadClass(this.clientHelper.getRetryHandler()).newInstance());
            } catch (Exception e) {
                this.clientHelper.getLogger().log(Level.WARNING,
                        "An error occurred during the instantiation of the retry handler.", e);
            }
        }

        this.responseHeadersAdded = false;
        setConfidential(this.httpMethod.getURI().getScheme().equalsIgnoreCase(Protocol.HTTPS.getSchemeName()));
    } else {
        throw new IllegalArgumentException("Only HTTP or HTTPS resource URIs are allowed here");
    }
}

From source file:com.wfreitas.camelsoap.SoapClient.java

public String sendRequest(String address, String message, String action) throws Exception {
    String responseBodyAsString;/*  w w  w  .j av  a  2 s .c o  m*/
    PostMethod postMethod = new PostMethod(address);
    try {
        HttpClient client = new HttpClient();
        postMethod.setRequestHeader("SOAPAction", action);
        postMethod.setRequestEntity(
                new InputStreamRequestEntity(new ByteArrayInputStream(message.getBytes("UTF-8")), "text/xml")

        );
        client.executeMethod(postMethod);
        responseBodyAsString = postMethod.getResponseBodyAsString();
    } finally {
        postMethod.releaseConnection();
    }

    return responseBodyAsString;
}

From source file:com.nfl.dm.clubsites.cms.articles.categorization.OpenCalaisRESTPost.java

private PostMethod createPostMethod() {
    PostMethod method = new PostMethod(CALAIS_URL);

    // Set mandatory parameters
    method.setRequestHeader("x-calais-licenseID", "sfna2j7bwgdfsnpvvjyudz2q");

    // Set input content type
    //method.setRequestHeader("Content-Type", "text/raw; charset=UTF-8");
    //method.setRequestHeader("Content-Type", "text/xml; charset=UTF-8");
    method.setRequestHeader("Content-Type", "text/html; charset=UTF-8");

    // Set response/output format
    //method.setRequestHeader("Accept", "xml/rdf");
    method.setRequestHeader("Accept", "application/json");

    // Enable Social Tags processing
    method.setRequestHeader("enableMetadataType", "SocialTags");

    return method;
}

From source file:fr.bettinger.log4j.HttpAppender.java

@Override
protected void append(LoggingEvent paramLoggingEvent) {
    /*//from  w  ww .  j av a  2s  . co  m
     * Dans le cas ou le layout n'est pas de type HttpLayout, on ne fait rien
     */
    if (!(this.getLayout() instanceof HttpLayout)) {
        errorHandler.error("you must use a HttpLayout type");
        return;
    }
    HttpLayout layout = (HttpLayout) getLayout();

    HttpMethodBase httpMethod = null;
    HttpClient httpClient = new HttpClient();
    /*
     * On positionne le timeout
     */
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeOut);
    httpClient.getParams().setSoTimeout(timeOut);

    if (this.HttpMethodBase.equalsIgnoreCase(METHOD_GET)) {
        String query = layout.format(paramLoggingEvent);
        String url = this.logURL + query;
        LogLog.debug(url);
        httpMethod = new GetMethod(url);
    } else {
        if (this.postMethod.equalsIgnoreCase(POST_PARAMETERS)) {
            httpMethod = new PostMethod(this.logURL);
            // post requests don't need to be encoded manually
            layout.urlEncode = false;
            for (int i = 0; i < layout.subLayouts.size(); i += 2) {
                URLParameterNameLayout nameLayout = (URLParameterNameLayout) layout.subLayouts.get(i);
                String value = layout.subLayouts.get(i + 1).format(paramLoggingEvent);
                ((PostMethod) httpMethod).addParameter(nameLayout.getValue(), value);
            }
        } else {
            String message = layout.format(paramLoggingEvent);
            StringBuffer sb = new StringBuffer(this.logURL);
            sb.append(message);
            httpMethod = new PostMethod(sb.toString());
        }
    }
    HttpThread httpThread = new HttpThread(httpClient, errorHandler);
    httpThread.setMethod(httpMethod);

    if (thread) {
        executorService.submit(httpThread);
    } else {
        httpThread.run();
    }
}

From source file:com.rallydev.integration.build.rest.RallyRestService.java

public String create(String artifact, String xml) throws IOException {
    return doCreate(xml, new HttpClient(), new PostMethod(getUrl() + "/" + artifact + "/create"));
}

From source file:modnlp.capte.AlignerUtils.java

@SuppressWarnings("deprecation")
/* This method creates the HTTP connection to the server 
 * and sends the POST request with the two files for alignment,
 * /*from ww w.j  av  a 2 s  . c  o  m*/
 * The server returns the aligned file as the response to the post request, 
 * which is delimited by the tag <beginalignment> which separates the file
 * from the rest of the POST request
 * 
 * 
 * 
 */
public static String MultiPartFileUpload(String source, String target) throws IOException {
    String response = "";
    String serverline = System.getProperty("capte.align.server"); //"http://ronaldo.cs.tcd.ie:80/~gplynch/aling.cgi";   
    PostMethod filePost = new PostMethod(serverline);
    // Send any XML file as the body of the POST request
    File f1 = new File(source);
    File f2 = new File(target);
    System.out.println(f1.getName());
    System.out.println(f2.getName());
    System.out.println("File1 Length = " + f1.length());
    System.out.println("File2 Length = " + f2.length());
    Part[] parts = {

            new StringPart("param_name", "value"), new FilePart(f2.getName(), f2),
            new FilePart(f1.getName(), f1) };
    filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
    HttpClient client = new HttpClient();
    int status = client.executeMethod(filePost);
    String res = "";
    InputStream is = filePost.getResponseBodyAsStream();
    Header[] heads = filePost.getResponseHeaders();
    Header[] feet = filePost.getResponseFooters();
    BufferedInputStream bis = new BufferedInputStream(is);

    String datastr = null;
    StringBuffer sb = new StringBuffer();
    byte[] bytes = new byte[8192]; // reading as chunk of 8192
    int count = bis.read(bytes);
    while (count != -1 && count <= 8192) {
        datastr = new String(bytes, "UTF8");

        sb.append(datastr);
        count = bis.read(bytes);
    }

    bis.close();
    res = sb.toString();

    System.out.println("----------------------------------------");
    System.out.println("Status is:" + status);
    //System.out.println(res);
    /* for debugging
    for(int i = 0 ;i < heads.length ;i++){
      System.out.println(heads[i].toString());
                   
    }
    for(int j = 0 ;j < feet.length ;j++){
      System.out.println(feet[j].toString());
                   
    }
    */
    filePost.releaseConnection();
    String[] handle = res.split("<beginalignment>");
    //Check for errors in the header
    // System.out.println(handle[0]);
    //Return the required text
    String ho = "";
    if (handle.length < 2) {
        System.out.println("Server error during alignment, check file encodings");
        ho = "error";
    } else {
        ho = handle[1];
    }
    return ho;

}

From source file:com.baidu.qa.service.test.client.HttpReqImpl.java

/**
 * use httpclient//from  ww w . java 2  s  .co  m
 * @param file
 * @param config
 * @param vargen
 * @return
 */
public Object requestHttpByHttpClient(File file, Config config, VariableGenerator vargen) {
    FileCharsetDetector det = new FileCharsetDetector();
    try {
        String oldcharset = det.guestFileEncoding(file);
        if (oldcharset.equalsIgnoreCase("UTF-8") == false)
            FileUtil.transferFile(file, oldcharset, "UTF-8");
    } catch (Exception ex) {
        log.error("[change expect file charset error]:" + ex);
    }

    Map<String, String> datalist = FileUtil.getMapFromFile(file, "=");
    if (datalist.size() <= 1) {
        return true;
    }
    if (!datalist.containsKey(Constant.KW_ITEST_HOST) && !datalist.containsKey(Constant.KW_ITEST_URL)) {
        log.error("[wrong file]:" + file.getName() + " hasn't Url");
        return null;
    }
    if (datalist.containsKey(Constant.KW_ITEST_HOST)) {
        this.url = datalist.get(Constant.KW_ITEST_HOST);
        this.hashost = true;
        datalist.remove(Constant.KW_ITEST_HOST);
    } else {
        String action = datalist.get(Constant.KW_ITEST_URL);
        if (config.getHost().lastIndexOf("/") == config.getHost().length() - 1 && action.indexOf("/") == 0) {
            action = action.substring(1);
        }
        this.url = config.getHost() + action;
        datalist.remove("itest_url");

    }
    if (datalist.containsKey(Constant.KW_ITEST_EXPECT)) {
        this.itest_expect = datalist.get(Constant.KW_ITEST_EXPECT);
        datalist.remove(Constant.KW_ITEST_EXPECT);
    }
    if (datalist.containsKey(Constant.KW_ITEST_JSON)) {
        this.itest_expect_json = datalist.get(Constant.KW_ITEST_JSON);
        datalist.remove(Constant.KW_ITEST_JSON);
    }
    parammap = datalist;
    this.config = config;

    //HttpClient
    HttpClient httpClient = new HttpClient();
    //
    httpClient.setConnectionTimeout(30000);
    httpClient.setTimeout(30000);
    httpClient.getParams().setParameter("http.protocol.content-charset", "UTF-8");
    PostMethod postMethod = new PostMethod(url);

    if (hashost == false) {
        //cookie copy
        if (config.getVariable() != null
                && config.getVariable().containsKey(Constant.V_CONFIG_VARIABLE_COOKIE)) {

            postMethod.addRequestHeader(Constant.V_CONFIG_VARIABLE_COOKIE,
                    (String) config.getVariable().get(Constant.V_CONFIG_VARIABLE_COOKIE));
            log.info("[HTTP Request Cookie]"
                    + (String) config.getVariable().get(Constant.V_CONFIG_VARIABLE_COOKIE));
        }
    }

    //??keysparams??body??key=value?
    if (parammap.size() == 1 && (parammap.containsKey("params") || parammap.containsKey("Params"))) {
        String key = "";
        if (parammap.containsKey("params")) {
            key = "params";
        } else if (parammap.containsKey("Params")) {
            key = "Params";
        }
        postMethod.setRequestHeader("Content-Type", "text/json;charset=utf-8");
        postMethod.setRequestBody(parammap.get(key).toString());
    } else {
        NameValuePair[] data = new NameValuePair[parammap.size()];
        int i = 0;
        for (Map.Entry<String, String> entry : parammap.entrySet()) {
            log.info("[HTTP post params]" + (String) entry.getKey() + ":" + (String) entry.getValue() + ";");
            if (entry.getValue().toString().contains("###")) {

            } else {
                data[i] = new NameValuePair((String) entry.getKey(), (String) entry.getValue());
            }
            i++;
        }
        // ?postMethod
        postMethod.setRequestBody(data);
    }

    Assert.assertNotNull("get request error,check the input file", postMethod);

    String response = "";
    // postMethod
    try {
        int statusCode = httpClient.executeMethod(postMethod);
        // HttpClient????POSTPUT???
        // 301302
        if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
            // ???
            Header locationHeader = postMethod.getResponseHeader("location");
            String location = null;
            if (locationHeader != null) {
                location = locationHeader.getValue();
                log.info("The page was redirected to:" + location);
            } else {
                log.info("Location field value is null.");
            }
        }

        //? 
        byte[] responseBody = postMethod.getResponseBody();
        if (responseBody == null) {
            log.error("[HTTP response is null]:please check login or servlet");
            return "";
        }
        //?utf-8
        response = new String(responseBody, "UTF-8");
        //?
        log.info("[The Post Request's Response][" + url + "]" + response);

        // responseoutput
        File resfile = FileUtil.rewriteFile(file.getParentFile().getParent() + Constant.FILENAME_OUTPUT,
                file.getName().substring(0, file.getName().indexOf(".")) + ".response", response);

        // 
        vargen.processProps(resfile);
        //??
        if (this.itest_expect != null && this.itest_expect.trim().length() != 0) {
            Assert.assertTrue(
                    "response different with expect:[expect]:" + this.itest_expect + "[actual]:" + response,
                    response.contains(this.itest_expect));
        }
        //                  if(this.itest_expect_json!=null&&this.itest_expect_json.trim().length()!=0){
        //                     VerifyJsonTypeResponseImpl.verifyResponseWithJson(this.itest_expect_json,response);
        //
        //                  }

    } catch (HttpException e) {
        //?????
        log.error("Please check your provided http address!" + e.getMessage());

    } catch (IOException e) {
        //?
        log.error(e.getMessage());
    } catch (Exception e) {
        log.error("[HTTP REQUEST ERROR]:", e);
        //case fail
        throw new RuntimeException("HTTP REQUEST ERROR:" + e.getMessage());
    } finally {
        //
        postMethod.releaseConnection();
    }
    return response;
}

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

@Test(enabled = TestConstants.EnabledTest)
public void testPresenceSolutionHill() {

    log.info("=== TEST for SOLUTION GENERATION of HILLCLIMB optimizer service 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.HILLCLIMB.toString());
    executeAndCheck(client, method);/*w w  w.  jav  a2s. c o  m*/

    log.info("=== TEST for SOLUTION GENERATION of HILLCLIMB optimizer service FINISEHD ===");

}

From source file:it.eng.spagobi.engines.talend.client.SpagoBITalendEngineClient_0_5_0.java

private String getEngineInfo(String infoType)
        throws EngineUnavailableException, ServiceInvocationFailedException {
    String version;/*  w  w  w .  j  av a2 s  .co m*/
    HttpClient client;
    PostMethod method;
    NameValuePair[] nameValuePairs;

    version = null;
    client = new HttpClient();
    method = new PostMethod(getServiceUrl(ENGINE_INFO_SERVICE));

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    nameValuePairs = new NameValuePair[] { new NameValuePair("infoType", infoType) }; //$NON-NLS-1$

    method.setRequestBody(nameValuePairs);

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

        if (statusCode != HttpStatus.SC_OK) {
            throw new ServiceInvocationFailedException(
                    Messages.getString("SpagoBITalendEngineClient_0_5_0.serviceExcFailed") //$NON-NLS-1$
                            + ENGINE_INFO_SERVICE,
                    method.getStatusLine().toString(),
                    method.getResponseBodyAsString());
        } else {
            version = method.getResponseBodyAsString();
        }

    } catch (HttpException e) {
        throw new EngineUnavailableException(
                Messages.getString("SpagoBITalendEngineClient_0_5_0.protocolViolation") + e.getMessage()); //$NON-NLS-1$
    } catch (IOException e) {
        throw new EngineUnavailableException(
                Messages.getString("SpagoBITalendEngineClient_0_5_0.transportError") + e.getMessage()); //$NON-NLS-1$
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    return version;
}