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:de.juwimm.cms.common.http.Server2ServerAuthenticationStreamSupportingHttpInvokerRequestExecutor.java

protected PostMethod createPostMethod(HttpInvokerClientConfiguration config) throws IOException {
    HttpClientWrapper.getInstance().setHostConfiguration(super.getHttpClient(),
            new URL(config.getServiceUrl()));
    PostMethod postMethod = new PostMethod(config.getServiceUrl());
    if (isAcceptGzipEncoding()) {
        postMethod.addRequestHeader(HTTP_HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
    }/*from  w ww .  ja v  a  2  s . c  o m*/
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if ((auth != null) && (auth.getName() != null) && (auth.getCredentials() != null)) {
        postMethod.setDoAuthentication(true);
        String base64 = auth.getName() + ":" + auth.getCredentials().toString();
        postMethod.addRequestHeader("Authorization",
                "Basic " + new String(Base64.encodeBase64(base64.getBytes())));

        if (log.isDebugEnabled()) {
            // log.debug("HttpInvocation now presenting via BASIC
            // authentication SecurityContextHolder-derived: " +
            // auth.toString());
            log.debug("HttpInvocation now presenting via BASIC authentication SecurityContextHolder-derived: "
                    + auth.getName());
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Unable to set BASIC authentication header as SecurityContext did not provide "
                    + "valid Authentication: " + auth);
        }
    }
    return postMethod;
}

From source file:greenfoot.export.mygame.MyGameClient.java

public final MyGameClient submit(String hostAddress, String uid, String password, String jarFileName,
        File sourceFile, File screenshotFile, int width, int height, ScenarioInfo info)
        throws UnknownHostException, IOException {
    String gameName = info.getTitle();
    String shortDescription = info.getShortDescription();
    String longDescription = info.getLongDescription();
    String updateDescription = info.getUpdateDescription();
    String gameUrl = info.getUrl();

    HttpClient httpClient = getHttpClient();
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(20 * 1000); // 20s timeout

    // Authenticate user and initiate session
    PostMethod postMethod = new PostMethod(hostAddress + "account/authenticate");

    postMethod.addParameter("user[username]", uid);
    postMethod.addParameter("user[password]", password);

    int response = httpClient.executeMethod(postMethod);

    if (response == 407 && listener != null) {
        // proxy auth required
        String[] authDetails = listener.needProxyAuth();
        if (authDetails != null) {
            String proxyHost = httpClient.getHostConfiguration().getProxyHost();
            int proxyPort = httpClient.getHostConfiguration().getProxyPort();
            AuthScope authScope = new AuthScope(proxyHost, proxyPort);
            Credentials proxyCreds = new UsernamePasswordCredentials(authDetails[0], authDetails[1]);
            httpClient.getState().setProxyCredentials(authScope, proxyCreds);

            // Now retry:
            response = httpClient.executeMethod(postMethod);
        }/*from  w  ww  .  j  a  va 2 s. c  om*/
    }

    if (response > 400) {
        error(Config.getString("export.publish.errorResponse") + " - " + response);
        return this;
    }

    // Check authentication result
    if (!handleResponse(postMethod)) {
        return this;
    }

    // Send the scenario and associated info
    List<String> tagsList = info.getTags();
    boolean hasSource = sourceFile != null;
    //determining the number of parts to send through
    //use a temporary map holder
    Map<String, String> partsMap = new HashMap<String, String>();
    if (info.isUpdate()) {
        partsMap.put("scenario[update_description]", updateDescription);
    } else {
        partsMap.put("scenario[long_description]", longDescription);
        partsMap.put("scenario[short_description]", shortDescription);
    }
    int size = partsMap.size();

    if (screenshotFile != null) {
        size = size + 1;
    }

    //base number of parts is 6
    int counter = 6;
    Part[] parts = new Part[counter + size + tagsList.size() + (hasSource ? 1 : 0)];
    parts[0] = new StringPart("scenario[title]", gameName, "UTF-8");
    parts[1] = new StringPart("scenario[main_class]", "greenfoot.export.GreenfootScenarioViewer", "UTF-8");
    parts[2] = new StringPart("scenario[width]", "" + width, "UTF-8");
    parts[3] = new StringPart("scenario[height]", "" + height, "UTF-8");
    parts[4] = new StringPart("scenario[url]", gameUrl, "UTF-8");
    parts[5] = new ProgressTrackingPart("scenario[uploaded_data]", new File(jarFileName), this);
    Iterator<String> mapIterator = partsMap.keySet().iterator();
    String key = "";
    String obj = "";
    while (mapIterator.hasNext()) {
        key = mapIterator.next().toString();
        obj = partsMap.get(key).toString();
        parts[counter] = new StringPart(key, obj, "UTF-8");
        counter = counter + 1;
    }

    if (hasSource) {
        parts[counter] = new ProgressTrackingPart("scenario[source_data]", sourceFile, this);
        counter = counter + 1;
    }
    if (screenshotFile != null) {
        parts[counter] = new ProgressTrackingPart("scenario[screenshot_data]", screenshotFile, this);
        counter = counter + 1;
    }

    int tagNum = 0;
    for (Iterator<String> i = tagsList.iterator(); i.hasNext();) {
        parts[counter] = new StringPart("scenario[tag" + tagNum++ + "]", i.next());
        counter = counter + 1;
    }

    postMethod = new PostMethod(hostAddress + "upload-scenario");
    postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));

    response = httpClient.executeMethod(postMethod);
    if (response > 400) {
        error(Config.getString("export.publish.errorResponse") + " - " + response);
        return this;
    }

    if (!handleResponse(postMethod)) {
        return this;
    }

    // Done.
    listener.uploadComplete(new PublishEvent(PublishEvent.STATUS));

    return this;
}

From source file:com.honnix.yaacs.adapter.http.ACHttpClient.java

private PostMethod buildPostMethod(String url, String request) {
    StringBuilder sb = new StringBuilder("http://").append(host).append(':').append(port).append(url);
    PostMethod postMethod = new PostMethod(sb.toString());

    sb = new StringBuilder(ACHttpConstant.HTTP_CONTENT_TYPE).append(" charset=").append(CHARSET);
    postMethod.setRequestHeader("Content-Type", sb.toString());

    try {//w w  w  .j  a  v a  2  s.  co  m
        StringRequestEntity requestEntity = new StringRequestEntity(request, null, CHARSET);

        postMethod.setRequestEntity(requestEntity);
    } catch (UnsupportedEncodingException e) {
        postMethod = null;
    }

    return postMethod;
}

From source file:es.carebear.rightmanagement.client.RestClient.java

public void getGroupsTest(String authName) throws IOException {
    HttpClient client = new HttpClient();

    PostMethod deleteMethod = new PostMethod(getServiceBaseURI() + "/client/groups/all/names");

    deleteMethod.addParameter("authName", "Admin");

    int responseCode = client.executeMethod(deleteMethod);

    String response = responseToString(deleteMethod.getResponseBodyAsStream());

    System.out.println(responseCode);

}

From source file:com.mycompany.neo4jprotein.neoStart.java

static public String createNode() {
    String output = null;//from ww  w.jav a  2 s  . co m
    String location = null;
    try {
        String nodePointUrl = SERVER_ROOT_URI + "/db/data/node/1";
        HttpClient client = new HttpClient();
        PostMethod mPost = new PostMethod(nodePointUrl);

        /**
         * set headers
         */
        Header mtHeader = new Header();
        mtHeader.setName("content-type");
        mtHeader.setValue("application/json");
        mtHeader.setName("accept");
        mtHeader.setValue("application/json");
        mPost.addRequestHeader(mtHeader);

        /**
         * set json payload
         */
        StringRequestEntity requestEntity = new StringRequestEntity("{}", "application/json", "UTF-8");
        mPost.setRequestEntity(requestEntity);
        int satus = client.executeMethod(mPost);
        output = mPost.getResponseBodyAsString();
        Header locationHeader = mPost.getResponseHeader("location");
        location = locationHeader.getValue();
        mPost.releaseConnection();
        System.out.println("satus : " + satus);
        System.out.println("location : " + location);
        System.out.println("output : " + output);
    } catch (Exception e) {
        System.out.println("Exception in creating node in neo4j : " + e);
    }

    return location;
}

From source file:cn.vlabs.umt.ui.servlet.OnlineStorageLoginServlet.java

private String getSid(HttpServletRequest request) {
    String uid = null;/*from  w ww  .j a  v a2  s  .  c o m*/
    ThirdPartyCredential tpc = (ThirdPartyCredential) request.getSession()
            .getAttribute(Attributes.THIRDPARTY_CREDENTIAL);
    if (tpc != null) {
        HttpClient client = new HttpClient(new MultiThreadedHttpConnectionManager());
        String loginThirdpartyAppURL = request.getParameter("loginThirdpartyAppURL");
        if (loginThirdpartyAppURL == null) {
            loginThirdpartyAppURL = "http://mail.cnic.cn/coremail/index.jsp";
        }
        PostMethod method = new PostMethod(loginThirdpartyAppURL);
        method.setParameter("uid", tpc.getUsername());
        method.setParameter("password", tpc.getPassword());
        method.setParameter("action:login", "");
        method.setParameter("face", "H");
        try {
            client.executeMethod(method);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        } finally {
            if (uid == null) {
                request.setAttribute("tip", "ssoLostPassword");
                request.setAttribute(Attributes.RETURN_URL, request.getParameter(Attributes.RETURN_URL));
            }
        }
        Header locationHeader = (Header) method.getResponseHeader("Location");
        if (locationHeader != null) {
            String location = locationHeader.getValue();
            uid = location.substring(location.lastIndexOf("?") + 5);
        }
        method.releaseConnection();
        client.getHttpConnectionManager().closeIdleConnections(0);
    } else {
        request.setAttribute("tip", "onlyCstnetUserLoginOnlineStorage");
    }
    return uid;
}

From source file:com.intellij.plugins.firstspirit.languagesupport.FirstSpiritClassPathHack.java

public void addFirstSpiritClientJar(UrlClassLoader classLoader, HttpScheme schema, String serverName, int port,
        String firstSpiritUserName, String firstSpiritUserPassword) throws Exception {
    System.out.println("starting to download fs-client.jar");

    String resolvalbleAddress = null;

    // asking DNS for IP Address, if some error occur choose the given value from user
    try {//from www.  jav  a2s.c o m
        InetAddress address = InetAddress.getByName(serverName);
        resolvalbleAddress = address.getHostAddress();
        System.out.println("Resolved address: " + resolvalbleAddress);
    } catch (Exception e) {
        System.err.println("DNS cannot resolve address, using your given value: " + serverName);
        resolvalbleAddress = serverName;
    }

    String uri = schema + "://" + resolvalbleAddress + ":" + port + "/clientjar/fs-client.jar";
    String versionUri = schema + "://" + resolvalbleAddress + ":" + port + "/version.txt";
    String tempDirectory = System.getProperty("java.io.tmpdir");

    System.out.println(uri);
    System.out.println(versionUri);

    HttpClient client = new HttpClient();
    HttpMethod getVersion = new GetMethod(versionUri);
    client.executeMethod(getVersion);
    String currentServerVersionString = getVersion.getResponseBodyAsString();
    System.out
            .println("FirstSpirit server you want to connect to is at version: " + currentServerVersionString);

    File fsClientJar = new File(tempDirectory, "fs-client-" + currentServerVersionString + ".jar");

    if (!fsClientJar.exists()) {
        // get an authentication cookie from FirstSpirit
        HttpMethod post = new PostMethod(uri);
        post.setQueryString("login.user=" + URLEncoder.encode(firstSpiritUserName, "UTF-8") + "&login.password="
                + URLEncoder.encode(firstSpiritUserPassword, "UTF-8") + "&login=webnonsso");
        client.executeMethod(post);
        String setCookieJsession = post.getResponseHeader("Set-Cookie").getValue();

        // download the fs-client.jar by using the authentication cookie
        HttpMethod get = new GetMethod(uri);
        get.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
        get.setRequestHeader("Cookie", setCookieJsession);
        client.executeMethod(get);

        InputStream inputStream = get.getResponseBodyAsStream();
        FileOutputStream outputStream = new FileOutputStream(fsClientJar);
        outputStream.write(IOUtils.readFully(inputStream, -1, false));
        outputStream.close();
        System.out.println("tempfile of fs-client.jar created within path: " + fsClientJar);
    }

    addFile(classLoader, fsClientJar);
}

From source file:edu.ku.brc.af.core.SpecialMsgNotifier.java

/**
 * @param item/*  w w w  . j a v  a 2s .c  om*/
 * @throws Exception
 */
protected String send(final String url, final String id) throws Exception {
    // check the website for the info about the latest version
    HttpClient httpClient = new HttpClient();
    httpClient.getParams().setParameter("http.useragent", getClass().getName()); //$NON-NLS-1$
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);

    PostMethod postMethod = new PostMethod(url);

    Vector<NameValuePair> postParams = new Vector<NameValuePair>();

    postParams.add(new NameValuePair("id", id)); //$NON-NLS-1$

    String resAppVersion = UIRegistry.getAppVersion();
    resAppVersion = StringUtils.isEmpty(resAppVersion) ? "Unknown" : resAppVersion;

    // get the OS name and version
    postParams.add(new NameValuePair("os_name", System.getProperty("os.name"))); //$NON-NLS-1$
    postParams.add(new NameValuePair("os_version", System.getProperty("os.version"))); //$NON-NLS-1$
    postParams.add(new NameValuePair("java_version", System.getProperty("java.version"))); //$NON-NLS-1$
    postParams.add(new NameValuePair("java_vendor", System.getProperty("java.vendor"))); //$NON-NLS-1$
    postParams.add(new NameValuePair("app_version", UIRegistry.getAppVersion())); //$NON-NLS-1$

    // create an array from the params
    NameValuePair[] paramArray = new NameValuePair[postParams.size()];
    for (int i = 0; i < paramArray.length; ++i) {
        paramArray[i] = postParams.get(i);
    }

    postMethod.setRequestBody(paramArray);

    // connect to the server
    try {
        httpClient.executeMethod(postMethod);

        int status = postMethod.getStatusCode();
        if (status == 200) {
            // get the server response
            String responseString = postMethod.getResponseBodyAsString();

            if (StringUtils.isNotEmpty(responseString)) {
                return responseString;
            }
        }
    } catch (java.net.UnknownHostException ex) {
        log.debug("Couldn't reach host.");

    } catch (Exception e) {
        e.printStackTrace();
        // die silently
    }
    return null;
}

From source file:edu.ucsd.xmlrpc.xmlrpc.client.XmlRpcCommonsTransport.java

protected PostMethod newPostMethod(XmlRpcHttpClientConfig pConfig) {
    return new PostMethod(pConfig.getServerURL().toString());
}

From source file:edu.ku.brc.ui.FeedBackSender.java

/**
 * @param item/*  w  w w  .  java  2 s. c o m*/
 * @throws Exception
 */
protected void send(final FeedBackSenderItem item) throws Exception {
    if (item != null) {
        // check the website for the info about the latest version
        HttpClient httpClient = new HttpClient();
        httpClient.getParams().setParameter("http.useragent", getClass().getName()); //$NON-NLS-1$

        PostMethod postMethod = new PostMethod(getSenderURL());

        // get the POST parameters (which includes usage stats, if we're allowed to send them)
        NameValuePair[] postParams = createPostParameters(item);
        postMethod.setRequestBody(postParams);

        // connect to the server
        try {
            httpClient.executeMethod(postMethod);

            // get the server response
            String responseString = postMethod.getResponseBodyAsString();

            if (StringUtils.isNotEmpty(responseString)) {
                System.err.println(responseString);
            }

        } catch (java.net.UnknownHostException uex) {
            log.error(uex.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}