Example usage for org.apache.commons.httpclient NameValuePair NameValuePair

List of usage examples for org.apache.commons.httpclient NameValuePair NameValuePair

Introduction

In this page you can find the example usage for org.apache.commons.httpclient NameValuePair NameValuePair.

Prototype

public NameValuePair(String name, String value) 

Source Link

Document

Constructor.

Usage

From source file:com.cyberway.issue.crawler.datamodel.credential.HtmlFormCredential.java

public boolean populate(CrawlURI curi, HttpClient http, HttpMethod method, String payload) {
    // http is not used.
    // payload is not used.
    boolean result = false;
    Map formItems = null;/*from w w  w .j  a v  a 2  s  . c  om*/
    try {
        formItems = getFormItems(curi);
    } catch (AttributeNotFoundException e1) {
        logger.severe("Failed get of form items for " + curi);
    }
    if (formItems == null || formItems.size() <= 0) {
        try {
            logger.severe("No form items for " + method.getURI());
        } catch (URIException e) {
            logger.severe("No form items and exception getting uri: " + e.getMessage());
        }
        return result;
    }

    NameValuePair[] data = new NameValuePair[formItems.size()];
    int index = 0;
    String key = null;
    for (Iterator i = formItems.keySet().iterator(); i.hasNext();) {
        key = (String) i.next();
        data[index++] = new NameValuePair(key, (String) formItems.get(key));
    }
    if (method instanceof PostMethod) {
        ((PostMethod) method).setRequestBody(data);
        result = true;
    } else if (method instanceof GetMethod) {
        // Append these values to the query string.
        // Get current query string, then add data, then get it again
        // only this time its our data only... then append.
        HttpMethodBase hmb = (HttpMethodBase) method;
        String currentQuery = hmb.getQueryString();
        hmb.setQueryString(data);
        String newQuery = hmb.getQueryString();
        hmb.setQueryString(((StringUtils.isNotEmpty(currentQuery)) ? currentQuery + "&" : "") + newQuery);
        result = true;
    } else {
        logger.severe("Unknown method type: " + method);
    }
    return result;
}

From source file:gov.nih.nci.cabio.portal.portlet.GlobalQueries.java

private void loadPathwaySources() {

    try {// w  ww .j  av a  2s. c o m
        log.info("Loading pathway data...");
        pathwaySources = new ArrayList<NameValuePair>();
        String hql = "select distinct source from gov.nih.nci.cabio.domain.Pathway";
        List<String> sources = as.query(new HQLCriteria(hql));
        for (String source : sources) {
            NameValuePair nv = new NameValuePair(source, source);
            pathwaySources.add(nv);
        }

        log.info("Done loading pathway data.");
    } catch (Exception e) {
        log.error("Error loading pathway data.", e);
    }
}

From source file:es.uvigo.ei.sing.jarvest.core.HTTPUtils.java

public synchronized static InputStream doPost(String urlstring, String queryString, String separator,
        Map<String, String> additionalHeaders, StringBuffer charsetb) throws HttpException, IOException {
    System.err.println("posting to: " + urlstring + ". query string: " + queryString);
    HashMap<String, String> query = parseQueryString(queryString, separator);
    HttpClient client = getClient();/* w  ww. j a va  2  s .co m*/

    URL url = new URL(urlstring);
    int port = url.getPort();
    if (port == -1) {
        if (url.getProtocol().equalsIgnoreCase("http")) {
            port = 80;
        }
        if (url.getProtocol().equalsIgnoreCase("https")) {
            port = 443;
        }
    }

    client.getHostConfiguration().setHost(url.getHost(), port, url.getProtocol());
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

    final PostMethod post = new PostMethod(url.getFile());
    addHeaders(additionalHeaders, post);
    post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    post.setRequestHeader("Accept", "*/*");
    // Prepare login parameters
    NameValuePair[] valuePairs = new NameValuePair[query.size()];

    int counter = 0;

    for (String key : query.keySet()) {
        //System.out.println("Adding pair: "+key+": "+query.get(key));
        valuePairs[counter++] = new NameValuePair(key, query.get(key));

    }

    post.setRequestBody(valuePairs);
    //authpost.setRequestEntity(new StringRequestEntity(requestEntity));

    client.executeMethod(post);

    int statuscode = post.getStatusCode();
    InputStream toret = null;
    if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
            || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
        Header header = post.getResponseHeader("location");
        if (header != null) {
            String newuri = header.getValue();
            if ((newuri == null) || (newuri.equals(""))) {
                newuri = "/";
            }

        } else {
            System.out.println("Invalid redirect");
            System.exit(1);
        }
    } else {
        charsetb.append(post.getResponseCharSet());
        final InputStream in = post.getResponseBodyAsStream();

        toret = new InputStream() {

            @Override
            public int read() throws IOException {
                return in.read();
            }

            @Override
            public void close() {
                post.releaseConnection();
            }

        };

    }

    return toret;
}

From source file:net.datapipe.CloudStack.CloudStackAPI.java

public Document deleteAutoScalePolicy(String id) throws Exception {
    LinkedList<NameValuePair> arguments = newQueryValues("deleteAutoScalePolicy", null);
    arguments.add(new NameValuePair("id", id));
    return Request(arguments);
}

From source file:com.zb.app.biz.service.WeixinTest.java

private boolean compareFakeid(String fakeid, String openid) {
    PostMethod post = new PostMethod(
            "https://mp.weixin.qq.com/cgi-bin/singlesendpage?t=message/send&action=index&token=" + token
                    + "&tofakeid=" + fakeid + "&lang=zh_CN");
    post.setRequestHeader("Cookie", this.cookiestr);
    post.setRequestHeader("Host", "mp.weixin.qq.com");
    post.setRequestHeader("Referer", "https://mp.weixin.qq.com/cgi-bin/contactmanage?t=user/index&token="
            + token + "&lang=zh_CN&pagesize=10&pageidx=0&type=0");
    post.setRequestHeader("Content-Type", "text/html;charset=UTF-8");
    post.addParameter(new NameValuePair("token", token));
    post.addParameter(new NameValuePair("ajax", "1"));
    try {//from  www  . ja  v  a2s.co m
        int code = httpClient.executeMethod(post);
        if (HttpStatus.SC_OK == code) {
            String str = post.getResponseBodyAsString();
            String msgJson = StringUtils.substringBetween(str, "<script id=\"json-msgList\" type=\"json\">",
                    "</script>");
            JSONParser parser = new JSONParser();
            try {
                JSONArray array = (JSONArray) parser.parse(msgJson);
                for (int i = 0; i < array.size(); i++) {
                    JSONObject obj = (JSONObject) array.get(i);
                    String content = (String) obj.get("content");
                    if (content.contains(openid)) {
                        return true;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

From source file:kevin.gvmsgarch.App.java

static String getInboxPage(String authToken, Worker.ListLocation location, int page) throws IOException {

    HttpClient client = new HttpClient();
    String retval = null;/* w  ww .  j a v a  2 s .co m*/

    GetMethod m = new GetMethod(location.getUri());
    if (page > 1) {
        m.setQueryString(new NameValuePair[] { new NameValuePair("page", "p" + page) });
    }
    m.setRequestHeader("Authorization", "GoogleLogin auth=" + authToken);
    int rcode;
    rcode = client.executeMethod(m);
    if (rcode != 200) {
        throw new RuntimeException("Received rcode: " + rcode);
    }
    retval = makeStringFromStream(m.getResponseBodyAsStream());
    return retval;
}

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;//www. jav  a 2  s.  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;

}

From source file:com.funambol.json.api.dao.AlternateJsonApiDao.java

/**
 *  search for application defined equivalent items for a specified item.
 * @return//from  www. j  a  v a 2  s.c  o  m
 */
@Override
public String getSyncItemKeysFromTwin(String itemToGetTwins, String itemKeyExpected)
        throws JSONTestAPIDAOException {

    if (log.isInfoEnabled()) {
        log.info("Executing method: getSyncItemKeysFromTwin()");
    }

    try {
        String content = configLoader.getJSONFile(this.getSourceName(), this.getTestName(), itemToGetTwins);

        if (log.isTraceEnabled()) {
            log.trace("content:" + content);
        }
        String req = configLoader.getServerProperty(Def.SERVER_URI) + "/" + this.getSourceName()
                + "/keys/twins";
        JSONObject jsonForTwins = JSONObject.fromObject(content).getJSONObject("data");
        String contentType = jsonForTwins.getString("content-type");
        jsonForTwins = jsonForTwins.getJSONObject("item");

        ArrayList<NameValuePair> requestProps = new ArrayList<NameValuePair>();
        if (contentType != null) {
            if (contentType.equals(Def.CONTENT_CARD)) {
                if (jsonForTwins.containsKey(Def.TWIN_FIRSTNAME)) {
                    requestProps
                            .add(new NameValuePair("firstname", jsonForTwins.optString(Def.TWIN_FIRSTNAME)));
                }
                if (jsonForTwins.containsKey(Def.TWIN_LASTNAME)) {
                    requestProps.add(new NameValuePair("lastname", jsonForTwins.optString(Def.TWIN_LASTNAME)));
                }
                if (jsonForTwins.containsKey(Def.TWIN_EMAIL)) {
                    requestProps.add(new NameValuePair("email", jsonForTwins.optString(Def.TWIN_EMAIL)));
                }
                if (jsonForTwins.containsKey(Def.TWIN_COMPANY)) {
                    requestProps
                            .add(new NameValuePair(Def.TWIN_COMPANY, jsonForTwins.optString(Def.TWIN_COMPANY)));
                }
            } else if (contentType.equals(Def.CONTENT_APPOINTMENT)) {
                if (jsonForTwins.containsKey(Def.TWIN_SUBJECT)) {
                    requestProps
                            .add(new NameValuePair(Def.TWIN_SUBJECT, jsonForTwins.optString(Def.TWIN_SUBJECT)));
                }
                if (jsonForTwins.containsKey(Def.TWIN_STARTDATE)) {
                    requestProps.add(new NameValuePair("dtstart", jsonForTwins.optString(Def.TWIN_STARTDATE)));
                }
                if (jsonForTwins.containsKey(Def.TWIN_ENDDATE)) {
                    requestProps.add(new NameValuePair("dtend", jsonForTwins.optString(Def.TWIN_ENDDATE)));
                }
            } else if (contentType.equals(Def.CONTENT_TASK)) {
                if (jsonForTwins.containsKey(Def.TWIN_SUBJECT)) {
                    requestProps.add(new NameValuePair("subject", jsonForTwins.optString(Def.TWIN_SUBJECT)));
                }
                if (jsonForTwins.containsKey(Def.TWIN_STARTDATE)) {
                    requestProps.add(new NameValuePair("dstart", jsonForTwins.optString(Def.TWIN_STARTDATE)));
                }
                if (jsonForTwins.containsKey(Def.TWIN_DUEDATE)) {
                    requestProps.add(new NameValuePair("dtend", jsonForTwins.optString(Def.TWIN_DUEDATE)));
                }
            } else if (contentType.equals(Def.CONTENT_NOTE)) {
                if (jsonForTwins.containsKey(Def.TWIN_SUBJECT)) {
                    requestProps.add(new NameValuePair("subject", jsonForTwins.optString(Def.TWIN_SUBJECT)));
                }
            }
        }
        if (requestProps.size() > 0) {
            NameValuePair[] n = new NameValuePair[requestProps.size()];
            Iterator it = requestProps.iterator();
            int i = 0;
            while (it.hasNext()) {
                n[i] = (NameValuePair) it.next();
                i++;
            }
            String response = sendGetRequestWithNameValuePairs(req, n);
            if (log.isTraceEnabled()) {
                log.trace("RESPONSE twins : \n" + response);
            }
            JSONArray twinItems = JSONObject.fromObject(response).getJSONObject("data").getJSONArray("keys");
            String keyExpected = configLoader.getKeyFromFile(this.getSourceName(), this.getTestName(),
                    itemKeyExpected, false);
            if (!twinItems.contains(keyExpected)) {
                if (log.isInfoEnabled()) {
                    log.info("ERROR the expected twin:" + keyExpected + " does not exist");
                }
            }
            return response;
        }

    } catch (IOOperationException ex) {
        throw new JSONTestAPIDAOException("Error retrieving twin items " + ex);
    }
    return "";
}

From source file:eu.learnpad.core.impl.cw.XwikiBridgeInterfaceRestResource.java

@Override
public void deleteRecommendations(String modelSetId, String simulationid, String userId)
        throws LpRestException {
    String contentType = "application/xml";

    HttpClient httpClient = this.getClient();
    String uri = String.format("%s/learnpad/cw/bridge/notify/deleterecs/%s", DefaultRestResource.REST_URI,
            modelSetId);//w w  w . j a v  a2 s.c  o m

    PutMethod putMethod = new PutMethod(uri);
    putMethod.addRequestHeader("Accept", contentType);

    NameValuePair[] queryString = new NameValuePair[2];
    queryString[0] = new NameValuePair("simulationid", simulationid);
    queryString[1] = new NameValuePair("userid", userId);
    putMethod.setQueryString(queryString);

    try {
        httpClient.executeMethod(putMethod);
    } catch (IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause());
    }
}

From source file:com.bigcommerce.http.QueryStringBuilder.java

/**
 * Adds a parameter to the list of already defined parameters. Already
 * existing parameters are overridden depending on the how the
 * <code>QueryStringBuilder</code> object was created.
 * <p>//from   w  w w .  ja v a2  s . c  o  m
 *
 * A value is considered as <i>invalid</i> if it is:
 * <ul>
 * <li><code>null</code> values
 * <li>empty values
 * <li>blank values
 * </ul>
 * Parameters with invalid values will <i>not</i> be added.
 *
 * @param name
 *            the name of the parameter
 * @param value
 *            the value of the parameter. The <code>toString</code> method
 *            will be invoked to retrieve the parameter's <i>real</i> value.
 * @param defaultValue
 *            the default value used in case the passed value argument is
 *            considered as invalid.
 *
 * @see #addQueryParameter(NameValuePair)
 */
public QueryStringBuilder addQueryParameter(final String name, final Object value, final String defaultValue) {
    String tmp = value == null || value.toString().trim().length() == 0 ? defaultValue
            : value.toString().trim();
    return addQueryParameter(new NameValuePair(name, tmp));
}