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:com.fluidops.iwb.wiki.WikiBot.java

/**
 * Execute a wikimedia query asking for the latest content of the
 * given wikipedia page. If {@link #expandTemplates} is set, the
 * templates within the content are automatically expanded
 *       /*from w  w w . ja  va2s  .c  om*/
 * @param wikiPage
 * @return
 */
private String retrieveWikiContent(String wikiPage) throws IOException, Exception {

    PostMethod method = new PostMethod(wikimediaApiURL());
    method.addRequestHeader("User-Agent", WIKIBOT_USER_AGENT);
    method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
    method.addParameter("action", "query");
    method.addParameter("prop", "revisions");
    method.addParameter("rvprop", "ids|content");
    if (expandTemplates)
        method.addParameter("rvexpandtemplates", "");
    method.addParameter("tlnamespace", "0");
    method.addParameter("format", "xml");
    method.addParameter("redirects", "");
    method.addParameter("titles", wikiPage.replace(" ", "_"));

    try {
        int status = httpClient.executeMethod(method);

        if (status == HttpStatus.SC_OK) {
            return parsePage(method.getResponseBodyAsStream());
        }

        throw new IOException("Error while retrieving wiki page " + wikiPage + ": " + status + " ("
                + method.getStatusText() + ")");
    } finally {
        method.releaseConnection();
    }
}

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

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

    log.info("=== TEST for SOLUTION GENERATION of BLIND 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", "BLINDSEARCH");

    executeAndCheck(client, method);/* www.j av a  2  s.  c  o  m*/

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

}

From source file:net.sf.xmm.moviemanager.http.HttpUtil.java

public boolean setUpIMDbAuthentication() {

    if (httpSettings == null) {
        log.warn("Authentication could not be set. Missing authentication settings.");
        return false;
    }//w w w  .  jav  a 2s  .c  o  m

    if (httpSettings.getIMDbAuthenticationEnabled()) {

        try {

            if (!isSetup())
                setup();

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

            PostMethod postMethod = new PostMethod(("https://secure.imdb.com/register-imdb/login"));

            NameValuePair[] postData = new NameValuePair[2];
            postData[0] = new NameValuePair("login", httpSettings.getIMDbAuthenticationUser());
            postData[1] = new NameValuePair("password", httpSettings.getIMDbAuthenticationPassword());

            postMethod.setRequestBody(postData);

            int statusCode = client.executeMethod(postMethod);

            if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
                imdbAuthenticationSetUp = true;
            else
                imdbAuthenticationSetUp = false;

        } catch (Exception e) {
            log.warn("error:" + e.getMessage());
        }
    } else
        imdbAuthenticationSetUp = false;

    return imdbAuthenticationSetUp;
}

From source file:ec.edu.ucuenca.dcc.sld.HttpUtils.java

public static synchronized String Http2(String s, Map<String, String> mp) throws SQLException, IOException {
    String resp = "";
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(s);
    method.getParams().setContentCharset("utf-8");

    client.getParams().setParameter("api-key", "58ef39e0-b91a-11e6-a057-97f4c970893c");
    client.getParams().setParameter("Content-Type", "application/json");

    //Add any parameter if u want to send it with Post req.
    for (Entry<String, String> mcc : mp.entrySet()) {
        method.addParameter(mcc.getKey(), mcc.getValue());
    }/*from w w  w .  j a v a 2s .  com*/

    int statusCode = client.executeMethod(method);

    if (statusCode != -1) {
        InputStream in = method.getResponseBodyAsStream();
        final Scanner reader = new Scanner(in, "UTF-8");
        while (reader.hasNextLine()) {
            final String line = reader.nextLine();
            resp += line + "\n";
        }
        reader.close();

    }

    return resp;
}

From source file:com.linkedin.pinot.common.utils.SchemaUtils.java

/**
 * Given host, port and schema, send a http POST request to upload the {@link Schema}.
 *
 * @return <code>true</code> on success.
 * <P><code>false</code> on failure.
 *//*from w  ww. ja v a  2s.com*/
public static boolean postSchema(@Nonnull String host, int port, @Nonnull Schema schema) {
    Preconditions.checkNotNull(host);
    Preconditions.checkNotNull(schema);

    try {
        URL url = new URL("http", host, port, "/schemas");
        PostMethod httpPost = new PostMethod(url.toString());
        try {
            Part[] parts = { new StringPart(schema.getSchemaName(), schema.toString()) };
            MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts, new HttpMethodParams());
            httpPost.setRequestEntity(requestEntity);
            int responseCode = HTTP_CLIENT.executeMethod(httpPost);
            if (responseCode >= 400) {
                String response = httpPost.getResponseBodyAsString();
                LOGGER.warn("Got error response code: {}, response: {}", responseCode, response);
                return false;
            }
            return true;
        } finally {
            httpPost.releaseConnection();
        }
    } catch (Exception e) {
        LOGGER.error("Caught exception while posting the schema: {} to host: {}, port: {}",
                schema.getSchemaName(), host, port, e);
        return false;
    }
}

From source file:ixa.pipe.wikify.DBpediaSpotlightClient.java

public Document extract(Text text, String host, String port) throws AnnotationException {

    LOG.info("Querying API.");
    String spotlightResponse = "";
    Document doc = null;/* ww w.  ja  va 2s . co m*/
    try {
        String url = host + ":" + port + "/rest/annotate";
        PostMethod method = new PostMethod(url);
        method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        NameValuePair[] params = { new NameValuePair("text", text.text()),
                new NameValuePair("confidence", Double.toString(CONFIDENCE)),
                new NameValuePair("support", Integer.toString(SUPPORT)),
                new NameValuePair("coreferenceResolution", Boolean.toString(COREFERENCE)) };
        method.setRequestBody(params);
        method.setRequestHeader(new Header("Accept", "text/xml"));
        spotlightResponse = request(method);
        doc = loadXMLFromString(spotlightResponse);
    } catch (javax.xml.parsers.ParserConfigurationException ex) {
    } catch (org.xml.sax.SAXException ex) {
    } catch (java.io.IOException ex) {
    }

    return doc;
}

From source file:ch.ksfx.web.services.spidering.http.HttpClientHelper.java

public PostMethod executePostMethod(String url, NameValuePair[] nameValuePairs) {
    try {//from   www  .ja  v  a 2 s .c om
        url = encodeURL(url);
        PostMethod postMethod = new PostMethod(url);
        postMethod.setFollowRedirects(false);
        postMethod.setRequestBody(nameValuePairs);
        postMethod = (PostMethod) executeMethod(postMethod);
        return postMethod;
    } catch (Exception e) {
        logger.severe("Error while generating POST method: " + e);
        return null;
    }
}

From source file:de.mpg.escidoc.http.Login.java

private String passLogin(Cookie securityCookie) {
    String userHandle = null;/*from   w ww . j  a  v  a2 s. c  o  m*/
    PostMethod postMethod = new PostMethod(this.FRAMEWORK_URL + "/aa/login");
    postMethod.addParameter("target", this.FRAMEWORK_URL);
    client.getState().addCookie(securityCookie);
    try {
        client.executeMethod(postMethod);

    } catch (HttpException e) {
        System.out.println("HttpException in login POST request");
        e.printStackTrace();
    } catch (IOException e) {
        System.out.println("IOException in login POST request");
        e.printStackTrace();
    }
    if (postMethod.getStatusCode() != 303) {
        System.out.println("StatusCode: " + postMethod.getStatusCode());
        return userHandle;
    }
    try {
        InputStream is = postMethod.getResponseBodyAsStream();
        System.out.println(Util.inputStreamToString(is));
    } catch (IOException e) {
        e.printStackTrace();
    }
    Header headers[] = postMethod.getResponseHeaders();
    for (int i = 0; i < headers.length; ++i) {
        System.out.println(headers[i]);
        if ("Location".equals(headers[i].getName())) {
            String location = headers[i].getValue();
            int index = location.indexOf('=');
            userHandle = new String(Base64.decode(location.substring(index + 1, location.length())));
            // System.out.println("location: " + location);
            System.out.println("UserHandle: " + userHandle);
        }
    }
    System.out.println(userHandle);
    return userHandle;
}

From source file:com.apatar.flickr.function.UploadPhotoFlickrTable.java

public List<KeyInsensitiveMap> execute(FlickrNode node, Hashtable<String, Object> values, String strApi,
        String strSecret) throws IOException, XmlRpcException {
    byte[] photo = (byte[]) values.get("photo");

    int size = values.size() + 2;

    values.remove("photo");

    File newFile = ApplicationData.createFile("flicr", photo);

    PostMethod post = new PostMethod("http://api.flickr.com/services/upload");
    Part[] parts = new Part[size];

    parts[0] = new FilePart("photo", newFile);
    parts[1] = new StringPart("api_key", strApi);
    int i = 2;/*  ww w .jav  a2 s. c o  m*/
    for (String key : values.keySet())
        parts[i++] = new StringPart(key, values.get(key).toString());

    values.put("api_key", strApi);

    parts[i] = new StringPart("api_sig", FlickrUtils.Sign(values, strApi, strSecret));

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

    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    int status = client.executeMethod(post);
    if (status != HttpStatus.SC_OK) {
        JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME,
                "Upload failed, response=" + HttpStatus.getStatusText(status));
        return null;
    } else {
        InputStream is = post.getResponseBodyAsStream();
        try {
            return createKeyInsensitiveMapFromElement(FlickrUtils.getRootElementFromInputStream(is));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:com.cloud.network.bigswitch.BigSwitchVnsApi.java

protected HttpMethod createMethod(String type, String uri, int port) throws BigSwitchVnsApiException {
    String url;/*from w w w  .  jav  a 2s  .  c  om*/
    try {
        url = new URL(s_protocol, _host, port, uri).toString();
    } catch (MalformedURLException e) {
        s_logger.error("Unable to build BigSwitch API URL", e);
        throw new BigSwitchVnsApiException("Unable to build v API URL", e);
    }

    if ("post".equalsIgnoreCase(type)) {
        return new PostMethod(url);
    } else if ("get".equalsIgnoreCase(type)) {
        return new GetMethod(url);
    } else if ("delete".equalsIgnoreCase(type)) {
        return new DeleteMethod(url);
    } else if ("put".equalsIgnoreCase(type)) {
        return new PutMethod(url);
    } else {
        throw new BigSwitchVnsApiException("Requesting unknown method type");
    }
}