Example usage for org.apache.http.client.utils URLEncodedUtils format

List of usage examples for org.apache.http.client.utils URLEncodedUtils format

Introduction

In this page you can find the example usage for org.apache.http.client.utils URLEncodedUtils format.

Prototype

public static String format(final Iterable<? extends NameValuePair> parameters, final Charset charset) 

Source Link

Document

Returns a String that is suitable for use as an application/x-www-form-urlencoded list of parameters in an HTTP PUT or HTTP POST.

Usage

From source file:org.xwiki.wysiwyg.internal.plugin.alfresco.server.TicketAuthenticator.java

@Override
public void authenticate(HttpRequestBase request) {
    String ticket = null;/* w  w w .j  ava2s.  c  o  m*/
    //get ticket from DB
    AlfrescoTiket dbTiket = ticketManager.getTicket();
    //if there is a ticket for current user,use it
    if (dbTiket != null) {
        ticket = dbTiket.getTiket();
    }
    /*if (ticket != null) {
    if (!ticketManager.validateAuthenticationTicket(ticket)) {
        //if ticket is not valid on alfresco, perform authentication
        ticket = getAuthenticationTicket();
    }
    } else {
    //if there is no ticket in DB, perform authentication
    ticket = getAuthenticationTicket();
    }*/

    // Add the ticket to the query string.
    URI uri = request.getURI();
    List<NameValuePair> parameters = URLEncodedUtils.parse(uri, QUERY_STRING_ENCODING);
    parameters.add(new BasicNameValuePair(AUTH_TICKET_PARAM, ticket));
    String query = URLEncodedUtils.format(parameters, QUERY_STRING_ENCODING);
    try {
        request.setURI(URIUtils.createURI(uri.getScheme(), uri.getHost(), uri.getPort(), uri.getRawPath(),
                query, uri.getRawFragment()));
    } catch (URISyntaxException e) {
        // This shouldn't happen.
    }
}

From source file:com.puppetlabs.puppetdb.javaclient.impl.HttpComponentsConnector.java

protected void assignContent(HttpEntityEnclosingRequestBase request, Map<String, String> params) {
    if (params != null && !params.isEmpty()) {
        List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
        for (Map.Entry<String, String> param : params.entrySet())
            pairs.add(new BasicNameValuePair(param.getKey(), param.getValue()));
        try {//from w  w w .ja  v  a2  s .c  om
            StringEntity entity = new StringEntity(URLEncodedUtils.format(pairs, UTF_8.name()), UTF_8.name());
            entity.setContentType(CONTENT_TYPE_WWW_FORM_URLENCODED);
            request.setEntity(entity);
        } catch (UnsupportedEncodingException e) {
            throw new IllegalArgumentException(e);
        }
    }
}

From source file:com.mp3tunes.android.player.RemoteAlbumArtHandler.java

private String getRemoteArtworkForLocalTrack(Track t) {
    String id = "stYqie5s3hGAz_VW3cXxwQ";
    String render = "json";
    String album = t.getAlbumTitle();
    String artist = t.getArtistName();
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("_id", id));
    params.add(new BasicNameValuePair("_render", render));
    params.add(new BasicNameValuePair("album", album));
    params.add(new BasicNameValuePair("artist", artist));

    try {/*  w  w w . j ava  2  s  . c  om*/
        URI uri = URIUtils.createURI("http", "pipes.yahoo.com", -1, "/pipes/pipe.run",
                URLEncodedUtils.format(params, "UTF-8"), null);

        HttpGet get = new HttpGet(uri);
        Log.w("Mp3Tunes", "Url: " + get.getURI().toString());

        HttpClient client = new DefaultHttpClient();
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String response = client.execute(get, responseHandler);
        client.getConnectionManager().shutdown();

        JSONObject obj = new JSONObject(response);
        JSONObject value = obj.getJSONObject("value");
        JSONArray items = value.getJSONArray("items");
        JSONObject item = items.getJSONObject(0);
        JSONObject image = item.getJSONObject("image");

        return image.getString("url");

    } catch (URISyntaxException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.aselalee.trainschedule.GetResultsFromSiteV2.java

private void GetResultsViaJSON(String station_from, String station_to, String time_from, String time_to,
        String date) {//from  ww w  .j  av a2s  .co  m
    /**
     * Create name value pairs to be sent.
     */
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(7);
    nameValuePairs.add(new BasicNameValuePair("lang", "en"));
    nameValuePairs.add(new BasicNameValuePair("startStationID", station_from));
    nameValuePairs.add(new BasicNameValuePair("endStationID", station_to));
    nameValuePairs.add(new BasicNameValuePair("startTime", time_from));
    nameValuePairs.add(new BasicNameValuePair("endTime", time_to));
    nameValuePairs.add(new BasicNameValuePair("searchDate", date));
    String strParams = URLEncodedUtils.format(nameValuePairs, "utf-8");
    strParams = Constants.JSONURL_GETSCH_V2 + "?" + strParams;
    String JSONStr = doJSONRequest(strParams);
    if (JSONStr == null) {
        results = null;
        resultsList = null;
        prices = null;
        return;
    }
    if (JSONToResultsList(JSONStr) == false) {
        results = null;
        resultsList = null;
        prices = null;
        return;
    }
}

From source file:services.plugins.atlassian.jira.jira1.client.JiraService.java

/**
 * Get the URI of an action./*from   ww  w. j av  a  2s .  c  om*/
 * 
 * @param action
 *            the action name
 * @param queryParams
 *            the query params
 */
private String getActionUri(String action, List<NameValuePair> queryParams) {
    try {
        URL url = new URL(getActionUrl(action));
        URI uri = url.toURI();

        String queryParamsString = "";
        if (queryParams != null && queryParams.size() > 0) {
            queryParamsString = "?" + URLEncodedUtils.format(queryParams, "UTF-8");
        }

        return uri.getPath() + queryParamsString;
    } catch (Exception e) {
        return null;
    }
}

From source file:com.revo.deployr.client.call.AbstractCall.java

protected RCoreResult makeGetRequest(String API) {

    List<NameValuePair> getParams = new ArrayList<NameValuePair>();
    for (Map.Entry<String, String> entry : httpParams.entrySet()) {
        getParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
    }//from  ww  w .jav a  2s  . com

    String encodedParams = URLEncodedUtils.format(getParams, "UTF-8");
    HttpGet httpGet = new HttpGet(serverUrl + API + "?" + encodedParams);

    return makeRequest(httpGet, API);
}

From source file:org.bibalex.gallery.model.BAGImage.java

public BAGImage(BAGGalleryAbstract gallery, BAGAlbum album, String name, long viewPaneWidth,
        long viewPaneHeight) throws BAGException {
    super();//www . j a  v a  2 s.  com
    this.gallery = gallery;
    this.album = album;
    this.name = name;
    HttpGet djatokaReq = null;
    try {

        this.highResUrlStr = this.gallery.getImageDirectAccUrlStr(album.getName(), name, EnumResolutions.high);

        // this.highResUrlEncoded = this.highResUrlStr.replaceAll(" ", "%20");
        // new URLCodec("US-ASCII").encode(this.highResUrlStr);

        this.thumbLocalUrl = this.gallery.getThumbLocalUrl(this.album.getName(), this.name);

        Integer tempFullWidth = null;
        Integer tempFullHeight = null;
        Integer tempZoomLevels = null;

        // Execute HTTP request
        this.httpclient = new DefaultHttpClient();

        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.add(new BasicNameValuePair("url_ver", "Z39.88-2004"));
        qparams.add(new BasicNameValuePair("rft_id", this.highResUrlStr)); // "http://memory.loc.gov/gmd/gmd433/g4330/g4330/np000066.jp2"));
        qparams.add(new BasicNameValuePair("svc_id", "info:lanl-repo/svc/getMetadata"));

        URI serverUri = new URI(gallery.getDjatokaServerUrlStr());

        URI reqUri = URIUtils.createURI(serverUri.getScheme(), serverUri.getHost(), serverUri.getPort(),
                serverUri.getPath(), URLEncodedUtils.format(qparams, "US-ASCII"), null);

        djatokaReq = new HttpGet(reqUri);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Getting metadata of image via URL: " + djatokaReq.getURI());
        }

        HttpResponse response = this.httpclient.execute(djatokaReq);

        if (response.getStatusLine().getStatusCode() / 100 != 2) {
            throw new BAGException("Connection error: " + response.getStatusLine().toString());
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Response from URL: " + djatokaReq.getURI() + " => " + response.getStatusLine());
        }

        // Get hold of the response entity
        HttpEntity entity = response.getEntity();

        // If the response does not enclose an entity, there is no need
        // to bother about connection release
        if ((entity != null)) {

            entity = new BufferedHttpEntity(entity);

            if ("application/json".equalsIgnoreCase(entity.getContentType().getValue())) {
                // Since the djatoka returned JSON is not properly escaped and I cannot find
                // any library that escapes JSON while parsing it I had to do this:
                String jsonString = EntityUtils.toString(entity);

                // remove the braces:
                jsonString = jsonString.substring(1);
                jsonString = jsonString.substring(0, jsonString.length() - 1);

                StringTokenizer pairTokens = new StringTokenizer(jsonString, ",", false);
                while (pairTokens.hasMoreElements()) {
                    String pair = pairTokens.nextToken().trim();

                    int colonIx = pair.indexOf(':');
                    String memberName = pair.substring(0, colonIx);
                    memberName = memberName.substring(1);
                    memberName = memberName.substring(0, memberName.length() - 1);

                    String memberValue = pair.substring(colonIx + 1).trim();
                    memberValue = memberValue.substring(memberValue.indexOf('"') + 1);
                    memberValue = memberValue.substring(0, memberValue.lastIndexOf('"'));

                    if ("width".equals(memberName)) {
                        tempFullWidth = Integer.valueOf(memberValue);
                    } else if ("height".equals(memberName)) {
                        tempFullHeight = Integer.valueOf(memberValue);
                    } else if ("levels".equals(memberName)) {
                        // FIXME replace "dwtLevels" by "levels" according to
                        // http://sourceforge.net/apps/mediawiki/djatoka/index.php?title=Djatoka_Level_Logic
                        // "dwtLevels" are the native JP2 DWT levels
                        tempZoomLevels = Integer.valueOf(memberValue);
                    }
                }

            }
        }

        if ((tempFullWidth == null) || (tempFullHeight == null) || (tempZoomLevels == null)) {
            throw new BAGException("Cannot retrieve metadata!");
        } else {
            this.fullWidth = tempFullWidth;
            this.fullHeight = tempFullHeight;
            this.zoomLevels = tempZoomLevels;
        }

    } catch (IOException ex) {

        // In case of an IOException the connection will be released
        // back to the connection manager automatically
        throw new BAGException(ex);

    } catch (RuntimeException ex) {

        // In case of an unexpected exception you may want to abort
        // the HTTP request in order to shut down the underlying
        // connection and release it back to the connection manager.
        djatokaReq.abort();
        throw ex;

    } catch (URISyntaxException e) {
        throw new BAGException(e);
        // } catch (EncoderException e) {
        // throw new BAGException(e);
    } finally {
        // connection kept alive and closed in finalize
    }

    this.djatokaParams = new ArrayList<NameValuePair>();
    this.djatokaParams.add(new BasicNameValuePair("url_ver", "Z39.88-2004"));
    this.djatokaParams.add(new BasicNameValuePair("rft_id", this.highResUrlStr)); // "http://memory.loc.gov/gmd/gmd433/g4330/g4330/np000066.jp2"));
    this.djatokaParams.add(new BasicNameValuePair("svc_id", "info:lanl-repo/svc/getRegion"));
    this.djatokaParams.add(new BasicNameValuePair("svc_val_fmt", "info:ofi/fmt:kev:mtx:jpeg2000"));
    this.djatokaParams.add(new BasicNameValuePair("svc.format", "image/jpeg"));

    this.zoomedX = 0;
    this.zoomedY = 0;
    this.zoomedWidth = this.fullWidth;
    this.zoomedHeight = this.fullHeight;
    this.zoomedRotate = 0;

    this.viewPaneHeight = viewPaneHeight;
    this.viewPaneWidth = viewPaneWidth;
    this.calculateDjatokaLevel();
    this.updateZoomedBytes();

    String lowResCache = URLPathStrUtils.appendParts(this.gallery.cacheLocalPath, "low");
    File tempJpg = new File(URLPathStrUtils.appendParts(lowResCache, name + ".jpg"));
    try {

        if (!tempJpg.exists()) {
            synchronized (BAGImage.class) {
                new File(lowResCache).mkdirs();
                tempJpg.createNewFile();
                FileOutputStream tempJpgOs = new FileOutputStream(tempJpg);
                ByteArrayInputStream temlJpgIS = new ByteArrayInputStream(this.zoomedBytes);
                try {
                    byte buffer[] = new byte[10240];
                    int bytesRead = 0;
                    do {
                        bytesRead = temlJpgIS.read(buffer);
                        if (bytesRead > 0) {
                            tempJpgOs.write(buffer, 0, bytesRead);
                        } else {
                            break;
                        }
                    } while (true);

                } finally {
                    tempJpgOs.flush();
                    tempJpgOs.close();

                }
            }
        }

    } catch (IOException e) {
        LOG.error("Couldn't create local cached version of low resolution version of: " + name);
        tempJpg = null;
    }
    if (tempJpg != null) {
        String ctxRootURL = new File(this.gallery.contextRootPath).toURI().toString();
        this.lowResLocalUrl = tempJpg.toURI().toString().substring(ctxRootURL.length());

    } else {
        this.lowResLocalUrl = this.thumbLocalUrl;
    }

}

From source file:org.craftercms.social.util.UGCHttpClient.java

public HttpResponse like(String ticket, String ugcId)
        throws URISyntaxException, ClientProtocolException, IOException {
    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("ticket", ticket));
    URI uri = URIUtils.createURI(scheme, host, port, appPath + "/api/2/ugc/like/" + ugcId + ".json",
            URLEncodedUtils.format(qparams, HTTP.UTF_8), null);
    HttpPost httppost = new HttpPost(uri);
    HttpClient httpclient = new DefaultHttpClient();
    return httpclient.execute(httppost);
}

From source file:gr.ntua.ivml.awareness.search.SearchServiceAccess.java

private URI constructURI(List<String> terms, String type, int startPage) {
    URI uri = null;/*from  w ww.ja  v  a 2s .  co  m*/
    String delim = "+";
    Iterator<String> it = terms.iterator();
    String q = "";
    if (it.hasNext()) {
        q = "\"" + it.next() + "\"";
    }
    while (it.hasNext()) {
        q += delim + "\"" + it.next() + "\"";
    }
    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("query", q));
    if (type != null && type.length() > 0) {
        qparams.add(new BasicNameValuePair("qf", "TYPE:" + type.toUpperCase()));
    }
    qparams.add(new BasicNameValuePair("profile", "standard"));

    if (startPage == 0)
        qparams.add(new BasicNameValuePair("start", "1"));
    else
        qparams.add(new BasicNameValuePair("start", Integer.toString(startPage * 6)));
    qparams.add(new BasicNameValuePair("rows", "6"));
    qparams.add(new BasicNameValuePair("wskey", "api2demo"));
    try {
        uri = URIUtils.createURI("http", "preview.europeana.eu", 80, "/api/v2/search.json",
                URLEncodedUtils.format(qparams, "UTF-8"), null);
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    return uri;
}

From source file:dataServer.StorageRESTClientManager.java

public List<RecommendationEvent> /*List<FeedbackEvent>*/ readFromStorage(String startDate, String endDate) {
    //        GetMethod get = new GetMethod("http://" + storageLocation + ":" + storagePort + storageContext + "/query/feedback/default/?startDate=" + startDate + "&endDate=" + endDate);
    // Default HTTP response and common properties for responses
    HttpResponse response = null;/*from www .j a v  a 2s. co  m*/
    ResponseHandler<String> handler = null;
    int status = 0;
    String body = null;
    // Default query for simple events
    requestUrl = new StringBuilder("http://" + storageLocation + ":" + storagePortRegistryC
            + storageRegistryContext + "/query/recommendation/default");

    params = new LinkedList<>();
    params.add(new BasicNameValuePair("startTime", startDate));
    params.add(new BasicNameValuePair("endTime", endDate));

    queryString = URLEncodedUtils.format(params, "utf-8");
    requestUrl.append("?");
    requestUrl.append(queryString);

    try {
        HttpGet query = new HttpGet(requestUrl.toString());
        query.setHeader("Content-type", "application/json");
        response = client.execute(query);

        // Check status code
        status = response.getStatusLine().getStatusCode();
        if (status != 200) {
            throw new RuntimeException("Failed! HTTP error code: " + status);
        }

        // Get body
        handler = new BasicResponseHandler();
        body = handler.handleResponse(response);

        //System.out.println("RECOMMENDATION.DEFAULT: " + body);
        // The result is an array of feedback events serialized as JSON using Apache Thrift.
        // The feedback events can be deserialized into Java objects using Apache Thrift.
        ObjectMapper mapper = new ObjectMapper();
        JsonNode nodeArray = mapper.readTree(body);
        List<RecommendationEvent> events = new ArrayList<>();
        for (JsonNode node : nodeArray) {
            byte[] bytes = node.toString().getBytes();
            TDeserializer deserializer = new TDeserializer(new TJSONProtocol.Factory());
            RecommendationEvent event = new RecommendationEvent();
            deserializer.deserialize(event, bytes);
            System.out.println(event.toString());
            events.add(event);
        }
        return events;
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
        return null;
    }

    ////        GetMethod get = new GetMethod("http://" + storageLocation + ":" + storagePort + storageContext + "/query/feedback/default/?startDate=" + startDate + "&endDate=" + endDate);
    //        // Default HTTP response and common properties for responses
    //        HttpResponse response = null;
    //        ResponseHandler<String> handler = null;
    //        int status = 0;
    //        String body = null;
    //        // Default query for simple events
    //        requestUrl = new StringBuilder("http://" + storageLocation + ":" + storagePort + storageContext + "/query/feedback/default");
    //
    //        params = new LinkedList<>();
    //        params.add(new BasicNameValuePair("startTime", startDate));
    //        params.add(new BasicNameValuePair("endTime", endDate));
    //
    //        queryString = URLEncodedUtils.format(params, "utf-8");
    //        requestUrl.append("?");
    //        requestUrl.append(queryString);
    //
    //        try {
    //            HttpGet query = new HttpGet(requestUrl.toString());
    //            query.setHeader("Content-type", "application/json");
    //            response = client.execute(query);
    //
    //            // Check status code
    //            status = response.getStatusLine().getStatusCode();
    //            if (status != 200) {
    //                throw new RuntimeException("Failed! HTTP error code: " + status);
    //            }
    //
    //            // Get body
    //            handler = new BasicResponseHandler();
    //            body = handler.handleResponse(response);
    //
    //            System.out.println("FEEDBACK.DEFAULT: " + body);
    //            // The result is an array of feedback events serialized as JSON using Apache Thrift.
    //            // The feedback events can be deserialized into Java objects using Apache Thrift.
    //            ObjectMapper mapper = new ObjectMapper();
    //            JsonNode nodeArray = mapper.readTree(body);
    //            List<FeedbackEvent> events = new ArrayList<>();
    //            for (JsonNode node : nodeArray) {
    //                byte[] bytes = node.toString().getBytes();
    //                TDeserializer deserializer = new TDeserializer(new TJSONProtocol.Factory());
    //                FeedbackEvent event = new FeedbackEvent();
    //                deserializer.deserialize(event, bytes);
    //                System.out.println(event.toString());
    //                events.add(event);
    //            }
    //            return events;
    //        } catch (Exception e) {
    //            System.out.println(e.getClass().getName() + ": " + e.getMessage());
    //            return null;
    //        }
}