Example usage for org.apache.commons.httpclient.params HttpMethodParams USE_EXPECT_CONTINUE

List of usage examples for org.apache.commons.httpclient.params HttpMethodParams USE_EXPECT_CONTINUE

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.params HttpMethodParams USE_EXPECT_CONTINUE.

Prototype

String USE_EXPECT_CONTINUE

To view the source code for org.apache.commons.httpclient.params HttpMethodParams USE_EXPECT_CONTINUE.

Click Source Link

Usage

From source file:com.polarion.alm.ws.client.internal.connection.CommonsHTTPSender.java

/**
 * invoke creates a socket connection, sends the request SOAP message and
 * then reads the response SOAP message back from the SOAP server
 * /*  w  w  w  .j  av  a  2  s . c  om*/
 * @param msgContext
 *            the messsage context
 * 
 * @throws AxisFault
 */
public void invoke(MessageContext msgContext) throws AxisFault {
    HttpMethodBase method = null;
    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage("enter00", "CommonsHTTPSender::invoke"));
    }
    try {
        URL targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL));

        // no need to retain these, as the cookies/credentials are
        // stored in the message context across multiple requests.
        // the underlying connection manager, however, is retained
        // so sockets get recycled when possible.
        HttpClient httpClient = new HttpClient(this.connectionManager);
        // the timeout value for allocation of connections from the pool
        httpClient.getParams().setConnectionManagerTimeout(this.clientProperties.getConnectionPoolTimeout());
        httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new RetryHandler());

        HostConfiguration hostConfiguration = getHostConfiguration(httpClient, msgContext, targetURL);

        boolean posting = true;

        // If we're SOAP 1.2, allow the web method to be set from the
        // MessageContext.
        if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
            String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD);
            if (webMethod != null) {
                posting = webMethod.equals(HTTPConstants.HEADER_POST);
            }
        }

        if (posting) {
            Message reqMessage = msgContext.getRequestMessage();
            method = new PostMethod(targetURL.toString());

            // set false as default, addContetInfo can overwrite
            method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);

            addContextInfo(method, httpClient, msgContext, targetURL);

            MessageRequestEntity requestEntity = null;
            if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
                requestEntity = new GzipMessageRequestEntity(method, reqMessage, httpChunkStream);
            } else {
                requestEntity = new MessageRequestEntity(method, reqMessage, httpChunkStream);
            }
            ((PostMethod) method).setRequestEntity(requestEntity);
        } else {
            method = new GetMethod(targetURL.toString());
            addContextInfo(method, httpClient, msgContext, targetURL);
        }

        String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
        if (httpVersion != null) {
            if (httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10)) {
                method.getParams().setVersion(HttpVersion.HTTP_1_0);
            }
            // assume 1.1
        }

        // don't forget the cookies!
        // Cookies need to be set on HttpState, since HttpMethodBase
        // overwrites the cookies from HttpState
        if (msgContext.getMaintainSession()) {
            HttpState state = httpClient.getState();
            method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
            String host = hostConfiguration.getHost();
            String path = targetURL.getPath();
            boolean secure = hostConfiguration.getProtocol().isSecure();
            fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE, host, path, secure);
            fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE2, host, path, secure);
            httpClient.setState(state);
        }

        int returnCode = httpClient.executeMethod(hostConfiguration, method, null);

        String contentType = getHeader(method, HTTPConstants.HEADER_CONTENT_TYPE);
        String contentLocation = getHeader(method, HTTPConstants.HEADER_CONTENT_LOCATION);
        String contentLength = getHeader(method, HTTPConstants.HEADER_CONTENT_LENGTH);

        if ((returnCode > 199) && (returnCode < 300)) {

            // SOAP return is OK - so fall through
        } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
            // For now, if we're SOAP 1.2, fall through, since the range of
            // valid result codes is much greater
        } else if ((contentType != null) && !contentType.equals("text/html")
                && ((returnCode > 499) && (returnCode < 600))) {

            // SOAP Fault should be in here - so fall through
        } else {
            String statusMessage = method.getStatusText();
            AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null);

            try {
                fault.setFaultDetailString(
                        Messages.getMessage("return01", "" + returnCode, method.getResponseBodyAsString()));
                fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode));
                throw fault;
            } finally {
                method.releaseConnection(); // release connection back to
                // pool.
            }
        }

        // wrap the response body stream so that close() also releases
        // the connection back to the pool.
        InputStream releaseConnectionOnCloseStream = createConnectionReleasingInputStream(method);

        Header contentEncoding = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
        if (contentEncoding != null) {
            if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP)) {
                releaseConnectionOnCloseStream = new GZIPInputStream(releaseConnectionOnCloseStream);
            } else {
                AxisFault fault = new AxisFault("HTTP",
                        "unsupported content-encoding of '" + contentEncoding.getValue() + "' found", null,
                        null);
                throw fault;
            }

        }
        Message outMsg = new Message(releaseConnectionOnCloseStream, false, contentType, contentLocation);
        // Transfer HTTP headers of HTTP message to MIME headers of SOAP
        // message
        Header[] responseHeaders = method.getResponseHeaders();
        MimeHeaders responseMimeHeaders = outMsg.getMimeHeaders();
        for (int i = 0; i < responseHeaders.length; i++) {
            Header responseHeader = responseHeaders[i];
            responseMimeHeaders.addHeader(responseHeader.getName(), responseHeader.getValue());
        }
        outMsg.setMessageType(Message.RESPONSE);
        msgContext.setResponseMessage(outMsg);
        if (log.isDebugEnabled()) {
            if (null == contentLength) {
                log.debug("\n" + Messages.getMessage("no00", "Content-Length"));
            }
            log.debug("\n" + Messages.getMessage("xmlRecd00"));
            log.debug("-----------------------------------------------");
            log.debug(outMsg.getSOAPPartAsString());
        }

        // if we are maintaining session state,
        // handle cookies (if any)
        if (msgContext.getMaintainSession()) {
            Header[] headers = method.getResponseHeaders();

            for (int i = 0; i < headers.length; i++) {
                if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE)) {
                    handleCookie(HTTPConstants.HEADER_COOKIE, headers[i].getValue(), msgContext);
                } else if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE2)) {
                    handleCookie(HTTPConstants.HEADER_COOKIE2, headers[i].getValue(), msgContext);
                }
            }
        }

        // always release the connection back to the pool if
        // it was one way invocation
        if (msgContext.isPropertyTrue("axis.one.way")) {
            method.releaseConnection();
        }

    } catch (Exception e) {
        log.debug(e);
        throw AxisFault.makeFault(e);
    }

    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage("exit00", "CommonsHTTPSender::invoke"));
    }
}

From source file:com.jaspersoft.ireport.jasperserver.ws.CommonsHTTPSender.java

/**
 * invoke creates a socket connection, sends the request SOAP message and then
 * reads the response SOAP message back from the SOAP server
 *
 * @param msgContext the messsage context
 *
 * @throws AxisFault/*from   ww  w. j ava 2  s.co m*/
 */
public void invoke(MessageContext msgContext) throws AxisFault {

    //test();

    HttpMethodBase method = null;
    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage("enter00", "CommonsHTTPSender::invoke"));
    }
    try {
        URL targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL));

        // no need to retain these, as the cookies/credentials are
        // stored in the message context across multiple requests.
        // the underlying connection manager, however, is retained
        // so sockets get recycled when possible.

        //org.apache.log4j.LogManager.getRootLogger().setLevel(org.apache.log4j.Level.DEBUG);

        HttpClient httpClient = new HttpClient(this.connectionManager);
        // the timeout value for allocation of connections from the pool
        httpClient.getParams().setConnectionManagerTimeout(this.clientProperties.getConnectionPoolTimeout());

        HostConfiguration hostConfiguration = getHostConfiguration(httpClient, msgContext, targetURL);

        boolean posting = true;

        // If we're SOAP 1.2, allow the web method to be set from the
        // MessageContext.
        if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
            String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD);
            if (webMethod != null) {
                posting = webMethod.equals(HTTPConstants.HEADER_POST);
            }
        }

        if (posting) {
            Message reqMessage = msgContext.getRequestMessage();
            method = new PostMethod(targetURL.toString());

            // set false as default, addContetInfo can overwrite
            method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);

            addContextInfo(method, httpClient, msgContext, targetURL);

            MessageRequestEntity requestEntity = null;
            if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
                requestEntity = new GzipMessageRequestEntity(method, reqMessage, httpChunkStream);
            } else {
                requestEntity = new MessageRequestEntity(method, reqMessage, httpChunkStream);
            }

            method.addRequestHeader(HTTPConstants.HEADER_CONTENT_LENGTH, "" + requestEntity.getContentLength());
            ((PostMethod) method).setRequestEntity(requestEntity);
        } else {
            method = new GetMethod(targetURL.toString());
            addContextInfo(method, httpClient, msgContext, targetURL);
        }

        String httpVersion = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION);
        if (httpVersion != null) {
            if (httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_V10)) {
                method.getParams().setVersion(HttpVersion.HTTP_1_0);
            }
            // assume 1.1
        }

        // don't forget the cookies!
        // Cookies need to be set on HttpState, since HttpMethodBase 
        // overwrites the cookies from HttpState
        if (msgContext.getMaintainSession()) {

            HttpState state = httpClient.getState();
            method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

            String host = targetURL.getHost();
            String path = targetURL.getPath();
            boolean secure = targetURL.getProtocol().equals("https");

            fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE, host, path, secure);
            fillHeaders(msgContext, state, HTTPConstants.HEADER_COOKIE2, host, path, secure);

            httpClient.setState(state);

        }

        int returnCode = httpClient.executeMethod(method);

        org.apache.log4j.LogManager.getRootLogger().setLevel(org.apache.log4j.Level.ERROR);

        String contentType = getHeader(method, HTTPConstants.HEADER_CONTENT_TYPE);
        String contentLocation = getHeader(method, HTTPConstants.HEADER_CONTENT_LOCATION);
        String contentLength = getHeader(method, HTTPConstants.HEADER_CONTENT_LENGTH);

        if ((returnCode > 199) && (returnCode < 300)) {

            // SOAP return is OK - so fall through
        } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) {
            // For now, if we're SOAP 1.2, fall through, since the range of
            // valid result codes is much greater
        } else if ((contentType != null) && !contentType.equals("text/html")
                && ((returnCode > 499) && (returnCode < 600))) {

            // SOAP Fault should be in here - so fall through
        } else {
            String statusMessage = method.getStatusText();
            AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null);

            try {
                fault.setFaultDetailString(
                        Messages.getMessage("return01", "" + returnCode, method.getResponseBodyAsString()));
                fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode));
                throw fault;
            } finally {
                method.releaseConnection(); // release connection back to pool.
            }
        }

        // wrap the response body stream so that close() also releases 
        // the connection back to the pool.
        InputStream releaseConnectionOnCloseStream = createConnectionReleasingInputStream(method);

        Header contentEncoding = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_ENCODING);
        if (contentEncoding != null) {
            if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP)) {
                releaseConnectionOnCloseStream = new GZIPInputStream(releaseConnectionOnCloseStream);
            } else {
                AxisFault fault = new AxisFault("HTTP",
                        "unsupported content-encoding of '" + contentEncoding.getValue() + "' found", null,
                        null);
                throw fault;
            }

        }
        Message outMsg = new Message(releaseConnectionOnCloseStream, false, contentType, contentLocation);
        // Transfer HTTP headers of HTTP message to MIME headers of SOAP message
        Header[] responseHeaders = method.getResponseHeaders();
        MimeHeaders responseMimeHeaders = outMsg.getMimeHeaders();
        for (int i = 0; i < responseHeaders.length; i++) {
            Header responseHeader = responseHeaders[i];
            responseMimeHeaders.addHeader(responseHeader.getName(), responseHeader.getValue());
        }
        outMsg.setMessageType(Message.RESPONSE);
        msgContext.setResponseMessage(outMsg);
        if (log.isDebugEnabled()) {
            if (null == contentLength) {
                log.debug("\n" + Messages.getMessage("no00", "Content-Length"));
            }
            log.debug("\n" + Messages.getMessage("xmlRecd00"));
            log.debug("-----------------------------------------------");
            log.debug(outMsg.getSOAPPartAsString());
        }

        // if we are maintaining session state,
        // handle cookies (if any)
        if (msgContext.getMaintainSession()) {
            Header[] headers = method.getResponseHeaders();

            for (int i = 0; i < headers.length; i++) {
                if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE)) {
                    handleCookie(HTTPConstants.HEADER_COOKIE, headers[i].getValue(), msgContext);
                } else if (headers[i].getName().equalsIgnoreCase(HTTPConstants.HEADER_SET_COOKIE2)) {
                    handleCookie(HTTPConstants.HEADER_COOKIE2, headers[i].getValue(), msgContext);
                }
            }
        }

        // always release the connection back to the pool if 
        // it was one way invocation
        if (msgContext.isPropertyTrue("axis.one.way")) {
            method.releaseConnection();
        }

    } catch (Exception e) {
        log.debug(e);
        throw AxisFault.makeFault(e);
    }

    if (log.isDebugEnabled()) {
        log.debug(Messages.getMessage("exit00", "CommonsHTTPSender::invoke"));
    }
}

From source file:com.tacitknowledge.maven.plugin.crx.CRXPackageInstallerPlugin.java

/**
 * @return the cookies return from this request on the login page.
 * @throws MojoExecutionException/*from  w ww.  java 2s .c  o m*/
 *             if any error occurs during this process.
 */
private Cookie[] getCookies() throws MojoExecutionException {
    Cookie[] cookie = null;
    GetMethod loginGet = new GetMethod(crxPath + "/login.jsp");
    loginGet.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
    try {
        getLog().info("login to " + loginGet.getURI());
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECTION_DEFAULT_TIMEOUT);
        int status = client.executeMethod(loginGet);
        // log the status
        getLog().info(
                "Response status: " + status + ", statusText: " + HttpStatus.getStatusText(status) + "\r\n");
        if (status == HttpStatus.SC_OK) {
            getLog().info("Login page accessed");
            cookie = client.getState().getCookies();
        } else {
            logResponseDetails(loginGet);
            throw new MojoExecutionException("Login failed, response=" + HttpStatus.getStatusText(status));
        }
    } catch (Exception ex) {
        getLog().error("ERROR: " + ex.getClass().getName() + " " + ex.getMessage());
        throw new MojoExecutionException(ex.getMessage());
    } finally {
        loginGet.releaseConnection();
    }
    return cookie;
}

From source file:com.tacitknowledge.maven.plugin.crx.CRXPackageInstallerPlugin.java

/**
 * @param cookies/*  w w w . jav a 2 s  .  c  o m*/
 *            get a session using the same existing previously requested
 *            response cookies.
 * @throws MojoExecutionException
 *             if any error occurred during this process.
 */
@SuppressWarnings("deprecation")
private void getSession(final Cookie[] cookies) throws MojoExecutionException {
    PostMethod loginPost = new PostMethod(crxPath + "/login.jsp");
    loginPost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
    try {
        getLog().info("login to " + loginPost.getPath());
        loginPost.setParameter("Workspace", workspace);
        loginPost.setParameter("UserId", login);
        loginPost.setParameter("Password", password);
        HttpClient client = new HttpClient();
        client.getState().setCookiePolicy(CookiePolicy.COMPATIBILITY);
        client.getState().addCookies(cookies);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECTION_DEFAULT_TIMEOUT);
        int status = client.executeMethod(loginPost);
        // log the status
        getLog().info(
                "Response status: " + status + ", statusText: " + HttpStatus.getStatusText(status) + "\r\n");
        if (status == HttpStatus.SC_MOVED_TEMPORARILY) {
            getLog().info("Login successful");
        } else {
            logResponseDetails(loginPost);
            throw new MojoExecutionException("Login failed, response=" + HttpStatus.getStatusText(status));
        }
    } catch (Exception ex) {
        getLog().error("ERROR: " + ex.getClass().getName() + " " + ex.getMessage());
        throw new MojoExecutionException(ex.getMessage());
    } finally {
        loginPost.releaseConnection();
    }
}

From source file:com.tacitknowledge.maven.plugin.crx.CRXPackageInstallerPlugin.java

/**
 * @param cookies/*from ww w. ja  va  2 s  .c o  m*/
 *            the previous requests cookies to keep in the same session.
 * @throws MojoExecutionException
 *             if any error occurs during this process.
 */
@SuppressWarnings("deprecation")
private void uploadPackage(final Cookie[] cookies) throws MojoExecutionException {
    PostMethod filePost = new PostMethod(crxPath + "/packmgr/list.jsp");
    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
    try {
        getLog().info("Uploading " + jarfile + " to " + filePost.getPath());
        File jarFile = new File(jarfile);
        Part[] parts = { new FilePart("file", jarFile) };
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
        HttpClient client = new HttpClient();
        client.getState().setCookiePolicy(CookiePolicy.COMPATIBILITY);
        client.getState().addCookies(cookies);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECTION_DEFAULT_TIMEOUT);
        int status = client.executeMethod(filePost);
        // log the status
        getLog().info(
                "Response status: " + status + ", statusText: " + HttpStatus.getStatusText(status) + "\r\n");
        if (status == HttpStatus.SC_MOVED_TEMPORARILY) {
            getLog().info("Upload complete");
        } else {
            logResponseDetails(filePost);
            throw new MojoExecutionException(
                    "Package upload failed, response=" + HttpStatus.getStatusText(status));
        }
    } catch (Exception ex) {
        getLog().error("ERROR: " + ex.getClass().getName() + " " + ex.getMessage());
        throw new MojoExecutionException(ex.getMessage());
    } finally {
        filePost.releaseConnection();
    }
}

From source file:com.celamanzi.liferay.portlets.rails286.OnlineClient.java

protected void createMultipartRequest(NameValuePair[] parametersBody, Map<String, Object[]> files,
        PostMethod method, List<File> tempFiles) throws IOException, FileNotFoundException {

    List<Part> parts = new ArrayList<Part>();
    parametersBody = removeFileParams(parametersBody, files);

    for (NameValuePair param : parametersBody) {
        parts.add(createStringPart(param));
    }/*from  ww w  .j  a v  a2  s .  c  o m*/

    for (String key : files.keySet()) {
        File file = createFile(files.get(key));
        if (file != null) {
            parts.add(new FilePart(key, file));
            tempFiles.add(file);
        }
    }

    Part[] array = new Part[parts.size()];
    method.setRequestEntity(new MultipartRequestEntity(parts.toArray(array), method.getParams()));

    method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
}

From source file:it.haefelinger.flaka.util.HttpUpload.java

public boolean upload() {
    File file = null;//  w  w w  . j  av a 2 s . c  om
    String endpoint = get("endpoint", HttpUpload.ENDPOINT);
    String testonly = get("testonly", HttpUpload.TESTONLY);
    String timeout = get("timeout", HttpUpload.TIMEOUT);
    String filepath = get("filepath", null);
    String logpath = get("logpath", null);
    String standard = get("standard", "1.0");

    syslog("endpoint: " + endpoint);
    syslog("testonly: " + testonly);
    syslog("timeouts: " + timeout);
    syslog("filepath: " + filepath);
    syslog("logpath : " + logpath);
    syslog("standard: " + standard);

    PostMethod filePost = null;
    boolean rc;

    try {
        /* new game */
        rc = false;
        setError(null);
        set("logmsg", "");

        if (testonly == null || testonly.matches("\\s*false\\s*")) {
            testonly = "x-do-not-test";
        } else {
            testonly = "test";
        }

        if (filepath == null || filepath.matches("\\s*")) {
            set("logmsg", "empty property `filepath', nothing to do.");
            return true;
        }

        /* loc to upload */
        file = new File(filepath);
        if (file.exists() == false) {
            setError("loc `" + file.getPath() + "' does not exist.");
            return false;
        }
        if (file.isFile() == false) {
            setError("loc `" + file.getPath() + "' exists but not a loc.");
            return false;
        }
        if (file.canRead() == false) {
            setError("loc `" + file.getPath() + "' can't be read.");
            return false;
        }

        set("filesize", "" + file.length());

        /* create HTTP method */
        filePost = new PostMethod(endpoint);

        Part[] parts = { new StringPart(testonly, "(opaque)"), filepart(file) };

        filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);

        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

        /* execute method */
        rc = exec(filePost) && eval(filePost);
    } finally {
        /* release resources in just any case */
        if (filePost != null)
            filePost.releaseConnection();
    }
    return rc;
}

From source file:is.idega.block.finance.business.sp.SPDataInsert.java

private void sendCreateClaimsRequest(BankFileManager bfm) {
    PostMethod filePost = new PostMethod(POST_METHOD);
    File file = new File(FILE_NAME);

    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);

    try {/*from w  ww  . j  a  v  a  2 s .c o  m*/
        StringPart userPart = new StringPart("notendanafn", bfm.getUsername());
        StringPart pwdPart = new StringPart("password", bfm.getPassword());
        StringPart clubssnPart = new StringPart("KtFelags", bfm.getClaimantSSN());
        FilePart filePart = new FilePart("Skra", file);

        Part[] parts = { userPart, pwdPart, clubssnPart, filePart };
        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) {
            System.out.println("Upload complete, response=" + filePost.getResponseBodyAsString());
        } else {
            System.out.println("Upload failed, response=" + HttpStatus.getStatusText(status));
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        filePost.releaseConnection();
    }
}

From source file:is.idega.block.finance.business.sp.SPDataInsertTest.java

private MultipartPostMethod sendCreateClaimsRequest() {
    /*//from  w  w w  . ja v  a2s .com
     * HttpClient client = new HttpClient(); client.setStrictMode(false);
     * MultipartPostMethod post = new MultipartPostMethod(SITE +
     * POST_METHOD); File file = new File(FILE_NAME);
     * 
     * try { post.addParameter("notendanafn", "lolo7452");// "aistest");
     * post.addParameter("password", "12345felix");
     * post.addParameter("KtFelags", "6812933379");// "5709902259");
     * post.addParameter("Skra", file);
     * 
     * post.setDoAuthentication(false); client.executeMethod(post);
     * 
     * System.out.println("responseString: " +
     * post.getResponseBodyAsString()); } catch (FileNotFoundException e1) {
     * e1.printStackTrace(); } catch (IOException e2) {
     * e2.printStackTrace(); } finally { post.releaseConnection(); } return
     * post;
     */

    PostMethod filePost = new PostMethod(SITE + POST_METHOD);
    File file = new File(FILE_NAME);

    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);

    try {
        StringPart userPart = new StringPart("notendanafn", "lolo7452");
        StringPart pwdPart = new StringPart("password", "12345felix");
        StringPart clubssnPart = new StringPart("KtFelags", "6812933379");
        FilePart filePart = new FilePart("Skra", file);

        Part[] parts = { userPart, pwdPart, clubssnPart, filePart };
        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) {
            System.out.println("Upload complete, response=" + filePost.getResponseBodyAsString());
        } else {
            System.out.println("Upload failed, response=" + HttpStatus.getStatusText(status));
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        filePost.releaseConnection();
    }

    return null;

    /*
     * PostMethod authpost = new PostMethod(SITE + POST_METHOD);
     * 
     * authpost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE,
     * true); try {
     * 
     * HttpClient client = new HttpClient();
     * client.getHttpConnectionManager().getParams().setConnectionTimeout(
     * 5000);
     * 
     * File file = new File(FILE_NAME); // Prepare login parameters
     * NameValuePair inputFile = new NameValuePair("xmldata", file);
     * authpost.setRequestBody(new NameValuePair[] { inputFile });
     * 
     * int status = client.executeMethod(authpost); System.out.println("Form
     * post: " + authpost.getStatusLine().toString()); if (status ==
     * HttpStatus.SC_OK) { System.out.println("Submit complete, response=" +
     * authpost.getResponseBodyAsString()); } else {
     * System.out.println("Submit failed, response=" +
     * HttpStatus.getStatusText(status)); } } catch (Exception ex) {
     * ex.printStackTrace(); } finally { authpost.releaseConnection(); }
     */

}

From source file:is.idega.block.finance.business.kb.KBDataInsert.java

/**
 * Sends a http multipart post method to KBBanki to create the claims
 * //from  w  w w  . ja  v a  2  s  .  c  o  m
 * @param bfm
 * @param groupId
 * @return
 */
private void sendCreateClaimsRequest(BankFileManager bfm) {
    /*      HttpClient client = new HttpClient();
          MultipartPostMethod post = new MultipartPostMethod(POST_METHOD);
          File file = new File(FILE_NAME);
                  
          System.out.println("!!!kb:");
          System.out.println("username = " + bfm.getUsername());
          System.out.println("password = " + bfm.getPassword());
                  
          try {
             post.addParameter("cguser", bfm.getUsername());// "IK66TEST"
             post.addParameter("cgpass", bfm.getPassword());// "KBIK66"
             post.addParameter("cgutli", "0");
             post.addParameter("cgskra", file);
             post.setDoAuthentication(false);
             client.executeMethod(post);
            
             System.out.println("responseString: "
       + post.getResponseBodyAsString());
            
          } catch (FileNotFoundException e1) {
             e1.printStackTrace();
          } catch (IOException e2) {
             e2.printStackTrace();
          } finally {
             post.releaseConnection();
          }
          return post;*/

    PostMethod filePost = new PostMethod(POST_METHOD);
    File file = new File(FILE_NAME);

    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);

    try {
        StringPart userPart = new StringPart("cguser", bfm.getUsername());
        StringPart pwdPart = new StringPart("password", bfm.getPassword());
        StringPart clubssnPart = new StringPart("cgclaimBatchName", batchName);
        FilePart filePart = new FilePart("cgskra", file);

        Part[] parts = { userPart, pwdPart, clubssnPart, filePart };
        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) {
            System.out.println("Upload complete, response=" + filePost.getResponseBodyAsString());
        } else {
            System.out.println("Upload failed, response=" + HttpStatus.getStatusText(status));
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        filePost.releaseConnection();
    }

}