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.mpg.mpdl.inge.util.AdminHelper.java

/**
 * Logs in the given user with the given password.
 * //from ww w  .j a va 2 s  .c o  m
 * @param userid The id of the user to log in.
 * @param password The password of the user to log in.
 * @return The handle for the logged in user.
 * @throws HttpException
 * @throws IOException
 * @throws ServiceException
 * @throws URISyntaxException
 */
public static String loginUser(String userid, String password)
        throws HttpException, IOException, ServiceException, URISyntaxException {
    String frameworkUrl = PropertyReader.getLoginUrl();

    int delim1 = frameworkUrl.indexOf("//");
    int delim2 = frameworkUrl.indexOf(":", delim1);

    String host;
    int port;

    if (delim2 > 0) {
        host = frameworkUrl.substring(delim1 + 2, delim2);
        port = Integer.parseInt(frameworkUrl.substring(delim2 + 1));
    } else {
        host = frameworkUrl.substring(delim1 + 2);
        port = 80;
    }
    HttpClient client = new HttpClient();

    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

    PostMethod login = new PostMethod(frameworkUrl + "/aa/j_spring_security_check");
    login.addParameter("j_username", userid);
    login.addParameter("j_password", password);

    ProxyHelper.executeMethod(client, login);

    login.releaseConnection();
    CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
    Cookie[] logoncookies = cookiespec.match(host, port, "/", false, client.getState().getCookies());

    Cookie sessionCookie = logoncookies[0];

    PostMethod postMethod = new PostMethod(frameworkUrl + "/aa/login");
    postMethod.addParameter("target", frameworkUrl);
    client.getState().addCookie(sessionCookie);
    ProxyHelper.executeMethod(client, postMethod);

    if (HttpServletResponse.SC_SEE_OTHER != postMethod.getStatusCode()) {
        throw new HttpException("Wrong status code: " + login.getStatusCode());
    }

    String userHandle = null;
    Header headers[] = postMethod.getResponseHeaders();
    for (int i = 0; i < headers.length; ++i) {
        if ("Location".equals(headers[i].getName())) {
            String location = headers[i].getValue();
            int index = location.indexOf('=');
            userHandle = new String(
                    Base64.getDecoder().decode(location.substring(index + 1, location.length())));
            // System.out.println("location: "+location);
            // System.out.println("handle: "+userHandle);
        }
    }

    if (userHandle == null) {
        throw new ServiceException("User not logged in.");
    }
    return userHandle;
}

From source file:ca.uvic.chisel.logging.eclipse.internal.network.LogUploadRunnable.java

public void run(IProgressMonitor sendMonitor) throws InterruptedException, InvocationTargetException {
    File[] filesToUpload = log.getCategory().getFilesToUpload();
    sendMonitor.beginTask("Uploading Log " + log.getCategory().getName(), filesToUpload.length);
    LoggingCategory category = log.getCategory();
    IMemento memento = category.getMemento();
    for (File file : filesToUpload) {
        if (sendMonitor.isCanceled()) {
            throw new InterruptedException();
        }/* w w  w  .  j a va 2s  . c om*/
        PostMethod post = new PostMethod(category.getURL().toString());

        try {
            Part[] parts = { new StringPart("KIND", "workbench-log"),
                    new StringPart("CATEGORY", category.getCategoryID()),
                    new StringPart("USER", WorkbenchLoggingPlugin.getDefault().getLocalUser()),
                    new FilePart("WorkbenchLogger", file.getName(), file, "application/zip", null) };
            post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
            HttpClient client = new HttpClient();
            int status = client.executeMethod(post);
            String resp = getData(post.getResponseBodyAsStream());
            if (status != 200 || !resp.startsWith("Status: 200 Success")) {
                IOException ex = new IOException(resp);
                throw (ex);
            }
            memento.putString("lastUpload", file.getName());
            file.delete();
        } catch (IOException e) {
            throw new InvocationTargetException(e);
        } finally {
            sendMonitor.worked(1);
        }
    }
    sendMonitor.done();
}

From source file:com.owncloud.android.lib.resources.users.SendCSROperation.java

/**
 * @param client Client object// www. j av a2s.  c o  m
 */
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    PostMethod postMethod = null;
    RemoteOperationResult result;

    try {
        // remote request
        postMethod = new PostMethod(client.getBaseUri() + PUBLIC_KEY_URL + JSON_FORMAT);
        postMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);
        postMethod.setParameter(CSR, csr);

        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 key = (String) respJSON.getJSONObject(NODE_OCS).getJSONObject(NODE_DATA)
                    .get(NODE_PUBLIC_KEY);

            result = new RemoteOperationResult(true, postMethod);
            ArrayList<Object> keys = new ArrayList<>();
            keys.add(key);
            result.setData(keys);
        } else {
            result = new RemoteOperationResult(false, postMethod);
            client.exhaustResponse(postMethod.getResponseBodyAsStream());
        }

    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Fetching of signing CSR failed: " + result.getLogMessage(), result.getException());
    } finally {
        if (postMethod != null)
            postMethod.releaseConnection();
    }
    return result;
}

From source file:it.geosolutions.httpproxy.utils.ProxyMethodConfig.java

/**
 * Obtain he method generation with {@link ProxyMethodConfig#method} and {@link ProxyMethodConfig#url}
 * //from  w  ww. jav a  2  s  . c  om
 * @return HttpMethod only supports {DELETE, GET, POST and PUT} @see {@link HttpMethods}
 */
public HttpMethod getMethod() {
    if (HttpMethods.METHOD_DELETE.equals(method)) {
        return new DeleteMethod(url.toExternalForm());
    } else if (HttpMethods.METHOD_GET.equals(method)) {
        return new GetMethod(url.toExternalForm());
    } else if (HttpMethods.METHOD_POST.equals(method)) {
        return new PostMethod(url.toExternalForm());
    } else if (HttpMethods.METHOD_PUT.equals(method)) {
        return new PutMethod(url.toExternalForm());
    } else {
        // Default is doGet
        return new GetMethod(url.toExternalForm());
    }
}

From source file:mesquite.tol.lib.BaseHttpRequestMaker.java

public static boolean postToServer(String s, String URI, StringBuffer response) {
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(URI);
    method.addParameter("OS", StringEscapeUtils
            .escapeHtml(System.getProperty("os.name") + "\t" + System.getProperty("os.version")));
    method.addParameter("JVM", StringEscapeUtils
            .escapeHtml(System.getProperty("java.version") + "\t" + System.getProperty("java.vendor")));
    NameValuePair post = new NameValuePair();
    post.setName("post");
    post.setValue(StringEscapeUtils.escapeHtml(s));
    method.addParameter(post);/* ww  w.  j a  va 2 s  .c  o  m*/

    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    return executeMethod(client, method, response);
}

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

/**
 * Create a login post method for the mascot server
 * @param username// w w w . ja  v  a  2  s .  c  o  m
 * @param password
 * @return the prepared post method
 * @throws java.lang.IllegalArgumentException
 */
private PostMethod loginMethod(String username, String password) {

    PostMethod authpost = new PostMethod("/mascot/cgi/login.pl");
    // Prepare login parameters
    NameValuePair[] arguments = { new NameValuePair("action", "login"), new NameValuePair("username", username),
            new NameValuePair("password", password), new NameValuePair("display", "logout_prompt"),
            new NameValuePair("savecookie", "1"), new NameValuePair("onerrdisplay", "login_prompt"), };
    authpost.setRequestBody(arguments);
    return authpost;
}

From source file:hydrograph.ui.communication.debugservice.method.Provider.java

/**
 * //from  w  w  w . j  a  v a2  s .com
 * Get post method to delete csv debug file
 * 
 * @param jobDetails
 * @return {@link PostMethod}
 * @throws NumberFormatException
 * @throws MalformedURLException
 */
public PostMethod getDeleteDebugFileMethod(JobDetails jobDetails)
        throws NumberFormatException, MalformedURLException {

    URL url = new URL(POST_PROTOCOL, getHost(jobDetails), getPortNo(jobDetails),
            DebugServiceMethods.DELETE_DEBUG_CSV_FILE);

    PostMethod postMethod = new PostMethod(url.toString());
    postMethod.addParameter(DebugServicePostParameters.JOB_ID, jobDetails.getUniqueJobID());
    postMethod.addParameter(DebugServicePostParameters.COMPONENT_ID, jobDetails.getComponentID());
    postMethod.addParameter(DebugServicePostParameters.SOCKET_ID, jobDetails.getComponentSocketID());

    LOGGER.debug("Calling debug service for deleting csv debug file url :: " + url);

    return postMethod;
}

From source file:de.knurt.fam.template.controller.letter.FamServicePDFResolver.java

/** {@inheritDoc} */
@Override/*from   ww w  . j  av a2s  .  c  o  m*/
@SuppressWarnings("deprecation")
// TODO #11 kill uses of deprecations
public PostMethod process(JSONObject datum) {

    // create connection
    Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
    Protocol.registerProtocol("https", easyhttps);

    // request configured fam-service-pdf
    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod(this.uri2Service);
    post.setQueryString(QueryStringFactory.get("json", datum.toString()).toString());

    // execute
    try {
        client.executeMethod(post);
    } catch (HttpException e) {
        FamLog.exception(e, 201106131407l);
    } catch (IOException e) {
        FamLog.exception(e, 201106131406l);
    }
    return post;
}

From source file:com.hw13c.HttpClientPost.java

private PostMethod createPostMethod() {

    PostMethod method = new PostMethod(CALAIS_URL);

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

    // Set input content type
    // method.setRequestHeader("Content-Type", "text/xml; charset=UTF-8");
    method.setRequestHeader("Content-Type", "text/html; charset=UTF-8");
    //method.setRequestHeader("Content-Type", "text/raw; 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:com.ebay.jetstream.application.dataflows.VisualDataFlow.java

private URL getYumlPic(String yumlData) {
    try {/*from w ww. j av a 2  s. c om*/
        if (!graphYuml.containsKey(yumlData)) {
            HttpClient httpclient = new HttpClient();
            PostMethod post = new PostMethod(yumlActivityUrl);
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            post.addParameter(new NameValuePair("dsl_text", yumlData));
            httpclient.executeMethod(post);
            URL url = new URL(yumlUrl + post.getResponseBodyAsString());
            graphYuml.put(yumlData, url);
            return url;
        } else {
            return graphYuml.get(yumlData);
        }
    } catch (Exception e) {
        logger.error(" Exception while rendering pipeline ", e);
        return null;
    }
}