Example usage for org.apache.commons.httpclient.methods PostMethod setRequestBody

List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestBody

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods PostMethod setRequestBody.

Prototype

public void setRequestBody(NameValuePair[] paramArrayOfNameValuePair) throws IllegalArgumentException 

Source Link

Usage

From source file:com.mirth.connect.client.core.UpdateClient.java

public void sendUsageStatistics() throws ClientException {
    // Only send stats if they haven't been sent in the last 24 hours.
    long now = System.currentTimeMillis();
    Long lastUpdate = client.getUpdateSettings().getLastStatsTime();

    if (lastUpdate != null) {
        long last = lastUpdate;
        // 86400 seconds in a day
        if ((now - last) < (86400 * 1000)) {
            return;
        }// ww w.  ja  va 2  s .c  o m
    }

    List<UsageData> usageData = null;

    try {
        usageData = getUsageData();
    } catch (Exception e) {
        throw new ClientException(e);
    }

    HttpClientParams httpClientParams = new HttpClientParams();
    HttpConnectionManager httpConnectionManager = new SimpleHttpConnectionManager();
    httpClientParams.setSoTimeout(10 * 1000);
    httpConnectionManager.getParams().setConnectionTimeout(10 * 1000);
    httpConnectionManager.getParams().setSoTimeout(10 * 1000);
    HttpClient httpClient = new HttpClient(httpClientParams, httpConnectionManager);

    PostMethod post = new PostMethod(client.getUpdateSettings().getUpdateUrl() + URL_USAGE_STATISTICS);
    NameValuePair[] params = { new NameValuePair("serverId", client.getServerId()),
            new NameValuePair("version", client.getVersion()),
            new NameValuePair("data", serializer.toXML(usageData)) };
    post.setRequestBody(params);

    try {
        int statusCode = httpClient.executeMethod(post);

        if ((statusCode != HttpStatus.SC_OK) && (statusCode != HttpStatus.SC_MOVED_TEMPORARILY)) {
            throw new Exception("Failed to connect to update server: " + post.getStatusLine());
        }

        // Save the sent time if sending was successful.
        UpdateSettings settings = new UpdateSettings();
        settings.setLastStatsTime(now);
        client.setUpdateSettings(settings);

    } catch (Exception e) {
        throw new ClientException(e);
    } finally {
        post.releaseConnection();
    }
}

From source file:edu.cmu.cs.diamond.pathfind.DjangoAnnotationStore.java

@Override
public void saveAnnotations(String qh1, SelectionListModel ssModel) throws IOException {
    // convert to jaxb
    RegionList rl = new RegionList();
    List<Region> regions = rl.getRegion();
    for (Annotation a : ssModel) {
        System.out.println("saving annotation: " + a);

        Region r = new Region();
        regions.add(r);/*w  w  w .j a  va 2 s .c om*/

        r.setPath(SlideAnnotation.shapeToString(a.getShape()));

        if (a instanceof SlideAnnotation) {
            SlideAnnotation sa = (SlideAnnotation) a;

            r.setId(sa.getId());

            NoteList nl = new NoteList();
            r.setNotes(nl);
            List<Note> notes = nl.getNote();

            for (SlideAnnotationNote n : sa.getNotes()) {
                Note nn = new Note();
                nn.setId(n.getId());
                nn.setText(n.getText());

                notes.add(nn);
            }
        }
    }

    // marshal it to a string to post
    StringWriter sw = new StringWriter();
    JAXB.marshal(new ObjectFactory().createRegions(rl), sw);

    try {
        String u = new URI(uriPrefix + qh1 + "/").toString();
        System.out.println(u);

        PostMethod post = new PostMethod(u);
        try {
            post.addRequestHeader("Referer", u);
            NameValuePair params[] = { new NameValuePair("xml", sw.toString()),
                    new NameValuePair("csrfmiddlewaretoken", csrftoken) };
            System.out.println(Arrays.toString(params));
            post.setRequestBody(params);

            int code = httpClient.executeMethod(post);
            code = maybeAuthenticate(post, code);

            System.out.println("post code: " + code);
            System.out.println(post.getResponseBodyAsString());
        } finally {
            post.releaseConnection();
        }
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
}

From source file:freeciv.servlet.ProxyServlet.java

/**
 * Performs an HTTP POST request// ww  w. j  av  a2s  . c o m
 * @param httpServletRequest The {@link HttpServletRequest} object passed
 *                            in by the servlet engine representing the
 *                            client request to be proxied
 * @param httpServletResponse The {@link HttpServletResponse} object by which
 *                             we can send a proxied response to the client 
 */
public void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws IOException, ServletException {

    // Create a standard POST request
    PostMethod postMethodProxyRequest = new PostMethod(this.getProxyURL(httpServletRequest));
    // Forward the request headers
    setProxyRequestHeaders(httpServletRequest, postMethodProxyRequest);
    // don't change Content-type header from client.
    //postMethodProxyRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    postMethodProxyRequest.setRequestBody(httpServletRequest.getInputStream());

    this.executeProxyRequest(postMethodProxyRequest, httpServletRequest, httpServletResponse);
    httpServletResponse.setHeader("Cache-Control", "no-cache"); //HTTP 1.1
    httpServletResponse.setHeader("Pragma", "no-cache"); //HTTP 1.0
    httpServletResponse.setDateHeader("Expires", 0); //prevents caching at the proxy server
}

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

private String getEngineInfo(String infoType)
        throws EngineUnavailableException, ServiceInvocationFailedException {
    String version;/*from  www .ja va 2  s  .  c o  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;
}

From source file:edu.cmu.cs.diamond.pathfind.DjangoAnnotationStore.java

private void login(String loginuri) throws IOException {
    String username = prefs.get("username", "");
    String password = "";

    JLabel label = new JLabel("Please enter your username and password:");
    JTextField jtf = new JTextField(username);
    JPasswordField jpf = new JPasswordField();
    int dialogResult = JOptionPane.showConfirmDialog(null, new Object[] { label, jtf, jpf },
            "Login to PathFind", JOptionPane.OK_CANCEL_OPTION);
    if (dialogResult == JOptionPane.OK_OPTION) {
        username = jtf.getText();//w ww.j av a  2s .  c o  m
        prefs.put("username", username);
        password = new String(jpf.getPassword());
    } else {
        throw new IOException("User refused to login");
    }

    // get the form to get the cookies
    GetMethod form = new GetMethod(loginuri);
    try {
        if (httpClient.executeMethod(form) != 200) {
            throw new IOException("Can't GET " + loginuri);
        }
    } finally {
        form.releaseConnection();
    }

    // get cookies
    Cookie[] cookies = httpClient.getState().getCookies();
    for (Cookie c : cookies) {
        System.out.println(c);
        if (c.getName().equals("csrftoken")) {
            csrftoken = c.getValue();
            break;
        }
    }

    // now, post
    PostMethod post = new PostMethod(loginuri);
    try {
        post.addRequestHeader("Referer", loginuri);
        NameValuePair params[] = { new NameValuePair("username", username),
                new NameValuePair("password", password), new NameValuePair("csrfmiddlewaretoken", csrftoken) };
        //System.out.println(Arrays.toString(params));
        post.setRequestBody(params);
        httpClient.executeMethod(post);
        System.out.println(post.getResponseBodyAsString());
    } finally {
        post.releaseConnection();
    }
}

From source file:ensen.controler.DBpediaSpotlightClient.java

private JSONArray getAnnotationsFromSpotlight(Text text, String confiance, String support, String file) {
    if (confiance == null || confiance.trim() == "")
        confiance = PropertiesManager.getProperty("CONFIDENCE");
    if (support == null || support.trim() == "")
        support = PropertiesManager.getProperty("SUPPORT");
    JSONArray entities = null;//w w w  .  java2  s .co  m
    if (local) {
        double d = Math.random();
        if (d > 0.5)
            API_URL = PropertiesManager.getProperty("DBpediaSpotlightClientLocal");
        else
            API_URL = PropertiesManager.getProperty("DBpediaSpotlightClientLocalCopy");
    } else
        API_URL = PropertiesManager.getProperty("DBpediaSpotlightClient");
    SPOTTER = PropertiesManager.getProperty("spotter");
    String spotlightResponse = null;
    try {
        //System.out.println("Querying API: " + API_URL);
        //System.err.println(text.text());
        /** using post **/
        PostMethod post = new PostMethod(API_URL + "rest/annotate/");
        NameValuePair[] data = { new NameValuePair("coreferenceResolution", "false"),
                /**//*new NameValuePair("disambiguator", "Document"),new NameValuePair("spotter", SPOTTER),*/new NameValuePair(
                        "confidence", confiance),
                new NameValuePair("support", support), new NameValuePair("text", text.text()) };
        post.setRequestBody(data);
        post.addRequestHeader(new Header("Accept", "application/json"));
        post.setRequestHeader("Content-Type", PostMethod.FORM_URL_ENCODED_CONTENT_TYPE + "; charset=UTF-8");
        spotlightResponse = request(post);

    } catch (Exception e) {
        System.err.println("error in calling Spotlight.");
    }

    JSONObject resultJSON = null;

    try {
        resultJSON = new JSONObject(spotlightResponse);
        if (resultJSON.has("Resources")) {
            entities = resultJSON.getJSONArray("Resources");
        } else {
            System.err.println("No founded resources");
            System.err.println(resultJSON);
        }
    } catch (JSONException e) {
        System.err.println(spotlightResponse);
        System.err.println("Received invalid response from DBpedia Spotlight API.");
        e.printStackTrace();
    }
    if (resultJSON != null) {
        //System.err.println("print json to" + file + ".json");
        //Printer.printToFile(file + ".json", resultJSON.toString());
    }
    //if not enough resources ==> re-do with conf 0.15
    if ((entities == null || entities.length() < Integer
            .parseInt(PropertiesManager.getProperty("MinNofAnnotatedResourcesInDocument")))
            && confiance != "0.15") {
        entities = getAnnotationsFromSpotlight(text, "0.15", support, file);

    }

    return entities;
}

From source file:mitm.common.security.ca.handlers.comodo.Tier2PartnerDetails.java

/**
 * Requests a certificate. Returns true if a certificate was successfully requested.    
 *///w ww  .  j  a  v a2 s. c om
public boolean retrieveDetails() throws CustomClientCertException {
    reset();

    if (StringUtils.isEmpty(loginName)) {
        throw new CustomClientCertException("loginName must be specified.");
    }

    if (StringUtils.isEmpty(loginPassword)) {
        throw new CustomClientCertException("loginPassword must be specified.");
    }

    PostMethod postMethod = new PostMethod(connectionSettings.getTier2PartnerDetailsURL());

    NameValuePair[] data = { new NameValuePair("loginName", loginName),
            new NameValuePair("loginPassword", loginPassword) };

    if (accountID != null) {
        data = (NameValuePair[]) ArrayUtils.add(data, new NameValuePair("accountID", accountID));
    }

    postMethod.setRequestBody(data);

    HTTPMethodExecutor executor = new HTTPMethodExecutor(connectionSettings.getTotalTimeout(),
            connectionSettings.getProxyInjector());

    executor.setConnectTimeout(connectionSettings.getConnectTimeout());
    executor.setReadTimeout(connectionSettings.getReadTimeout());

    try {
        executor.executeMethod(postMethod, responseHandler);
    } catch (IOException e) {
        throw new CustomClientCertException(e);
    }

    return !error;
}

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

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

    LOG.info("Querying API.");
    String spotlightResponse = "";
    Document doc = null;/*from w  w  w  . j  av  a2 s . co m*/
    try {
        String url = host + ":" + port + "/rest/" + endpoint;

        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("spotter", "SpotXmlParser"),
                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:com.sfs.jbtimporter.JBTProcessor.java

/**
 * Post the data to the service.//from w  w w .j a v a  2  s.  co m
 *
 * @param postMethod the post method
 * @param data the data
 * @return the string
 * @throws IOException Signals that an I/O exception has occurred.
 */
private String postData(final PostMethod postMethod, final NameValuePair[] data) throws IOException {

    final StringBuffer raw = new StringBuffer();

    postMethod.setRequestBody(data);

    // Execute the post request
    httpClient.executeMethod(postMethod);

    try {
        Reader reader = new InputStreamReader(postMethod.getResponseBodyAsStream(),
                postMethod.getResponseCharSet());
        // consume the response entity
        int dataread = reader.read();
        while (dataread != -1) {
            char theChar = (char) dataread;
            raw.append(theChar);
            dataread = reader.read();
        }
    } finally {
        postMethod.releaseConnection();
    }
    return raw.toString();
}

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

public JSONObject extractJSON(TextAdaptation text, String host, String port, String endpoint)
        throws AnnotationException {

    LOG.info("Querying API.");
    String spotlightResponse = "";
    Document doc = null;/*from www . ja v  a2s  .  c  o  m*/
    try {
        String url = host + ":" + port + "/rest/" + endpoint;

        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("spotter", "SpotXmlParser"),
                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", "application/json"));
        spotlightResponse = request(method);
    } catch (Exception e) {
        throw new AnnotationException("Could not encode text.", e);
    }

    assert spotlightResponse != null;
    JSONObject resultJSON = null;

    try {
        resultJSON = new JSONObject(spotlightResponse);
    } catch (JSONException e) {
        throw new AnnotationException("Received invalid response from DBpedia Spotlight API.");
    }

    return resultJSON;

}