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:dataServer.StorageRESTClientManager.java

public String getMouldProperties(String mouldId) {
    // Default HTTP client and common properties for requests
    requestUrl = null;/* ww w . j  ava2 s  . co  m*/
    params = null;
    queryString = null;

    // Default HTTP response and common properties for responses
    HttpResponse response = null;
    ResponseHandler<String> handler = null;
    int status = 0;
    String body = null;

    // Query for mould properties
    requestUrl = new StringBuilder("http://" + storageLocation + ":" + storagePortRegistryC
            + storageRegistryContext + "/query/mould/properties");

    params = new LinkedList<NameValuePair>();
    params.add(new BasicNameValuePair("sensorId", mouldId));

    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("MOULD PROPRIETIES: " + body);
        return body;
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
        return null;
    }
}

From source file:de.geeksfactory.opacclient.apis.Zones.java

@Override
public ReservationResult reservation(DetailledItem item, Account acc, int useraction, String selection)
        throws IOException {
    String reservation_info = item.getReservation_info();
    String html = httpGet(opac_url + "/" + reservation_info, getDefaultEncoding());
    Document doc = Jsoup.parse(html);
    if (html.contains("Geheimnummer")) {
        List<NameValuePair> params = new ArrayList<>();
        for (Element input : doc.select("#MainForm input")) {
            if (!input.attr("name").equals("BRWR") && !input.attr("name").equals("PIN")) {
                params.add(new BasicNameValuePair(input.attr("name"), input.attr("value")));
            }/*from   w  w w.  j  a va 2s .c om*/
        }
        params.add(new BasicNameValuePair("BRWR", acc.getName()));
        params.add(new BasicNameValuePair("PIN", acc.getPassword()));
        html = httpGet(opac_url + "/" + doc.select("#MainForm").attr("action") + "?"
                + URLEncodedUtils.format(params, getDefaultEncoding()), getDefaultEncoding());
        doc = Jsoup.parse(html);
    }

    if (useraction == ReservationResult.ACTION_BRANCH) {
        List<NameValuePair> params = new ArrayList<>();
        for (Element input : doc.select("#MainForm input")) {
            if (!input.attr("name").equals("Confirm")) {
                params.add(new BasicNameValuePair(input.attr("name"), input.attr("value")));
            }

        }
        params.add(new BasicNameValuePair("MakeResTypeDef.Reservation.RecipientLocn", selection));
        params.add(new BasicNameValuePair("Confirm", "1"));
        httpGet(opac_url + "/" + doc.select("#MainForm").attr("action") + "?"
                + URLEncodedUtils.format(params, getDefaultEncoding()), getDefaultEncoding());
        return new ReservationResult(MultiStepResult.Status.OK);
    }

    if (useraction == 0) {
        ReservationResult res = null;
        for (Node n : doc.select("#MainForm").first().childNodes()) {
            if (n instanceof TextNode) {
                if (((TextNode) n).text().contains("Entgelt")) {
                    res = new ReservationResult(ReservationResult.Status.CONFIRMATION_NEEDED);
                    List<String[]> details = new ArrayList<>();
                    details.add(new String[] { ((TextNode) n).text().trim() });
                    res.setDetails(details);
                    res.setMessage(((TextNode) n).text().trim());
                    res.setActionIdentifier(MultiStepResult.ACTION_CONFIRMATION);
                }
            }
        }
        if (res != null) {
            return res;
        }
    }
    if (doc.select("#MainForm select").size() > 0) {
        ReservationResult res = new ReservationResult(ReservationResult.Status.SELECTION_NEEDED);
        List<Map<String, String>> sel = new ArrayList<>();
        for (Element opt : doc.select("#MainForm select option")) {
            Map<String, String> selopt = new HashMap<>();
            selopt.put("key", opt.attr("value"));
            selopt.put("value", opt.text().trim());
            sel.add(selopt);
        }
        res.setSelection(sel);
        res.setMessage("Bitte Zweigstelle auswhlen");
        res.setActionIdentifier(ReservationResult.ACTION_BRANCH);
        return res;
    }

    return new ReservationResult(ReservationResult.Status.ERROR);
}

From source file:com.esri.geoevent.datastore.GeoEventDataStoreProxy.java

private HttpPost createPostRequest(URI uri, String postBody, String contentTypes, ServerInfo serverInfo) {
    HttpPost httpPost = new HttpPost(uri);
    ContentType contentType = ContentType.create(contentTypes);
    if (contentType == null)
        throw new RuntimeException("Couldn't create content types for " + contentTypes);

    if (ContentType.APPLICATION_FORM_URLENCODED.getMimeType().equals(contentType.getMimeType())) {
        String tokenToUse = null;
        if (serverInfo.encryptedToken != null) {
            try {
                tokenToUse = Crypto.doDecrypt(serverInfo.encryptedToken);
            } catch (GeneralSecurityException e) {
                throw new RuntimeException(e);
            }//  w ww .  j  a  va2s .  co m
        }
        List<NameValuePair> params = parseQueryStringAndAddToken(postBody, tokenToUse);
        postBody = URLEncodedUtils.format(params, "UTF-8");
    }

    StringEntity entity = new StringEntity(postBody, contentType);
    httpPost.setEntity(entity);

    return httpPost;
}

From source file:org.opendatakit.dwc.server.GreetingServiceImpl.java

@Override
public String getOauth2UserEmail() throws IllegalArgumentException {

    // get the auth code...
    Context ctxt = getStateContext(ctxtKey);
    String code = (String) ctxt.getContext("code");
    {// w  w w.j  av a2s. c  om
        // convert the auth code into an auth token
        URI nakedUri;
        try {
            nakedUri = new URI(tokenUrl);
        } catch (URISyntaxException e2) {
            e2.printStackTrace();
            logger.error(e2.toString());
            return getSelfUrl();
        }

        // DON'T NEED clientId on the toke request...
        // addCredentials(clientId, clientSecret, nakedUri.getHost());
        // setup request interceptor to do preemptive auth
        // ((DefaultHttpClient) client).addRequestInterceptor(getPreemptiveAuth(), 0);

        HttpClientFactory factory = new GaeHttpClientFactoryImpl();

        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS);
        HttpConnectionParams.setSoTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS);
        // support redirecting to handle http: => https: transition
        HttpClientParams.setRedirecting(httpParams, true);
        // support authenticating
        HttpClientParams.setAuthenticating(httpParams, true);

        httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 1);
        httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        // setup client
        HttpClient client = factory.createHttpClient(httpParams);

        HttpPost httppost = new HttpPost(nakedUri);
        logger.info(httppost.getURI().toString());

        // THESE ARE POST BODY ARGS...    
        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.add(new BasicNameValuePair("grant_type", "authorization_code"));
        qparams.add(new BasicNameValuePair("client_id", CLIENT_ID));
        qparams.add(new BasicNameValuePair("client_secret", CLIENT_SECRET));
        qparams.add(new BasicNameValuePair("code", code));
        qparams.add(new BasicNameValuePair("redirect_uri", getOauth2CallbackUrl()));
        UrlEncodedFormEntity postentity;
        try {
            postentity = new UrlEncodedFormEntity(qparams, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
            logger.error(e1.toString());
            throw new IllegalArgumentException("Unexpected");
        }

        httppost.setEntity(postentity);

        HttpResponse response = null;
        try {
            response = client.execute(httppost, localContext);
            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode != HttpStatus.SC_OK) {
                logger.error("not 200: " + statusCode);
                return "Error with Oauth2 token request - reason: " + response.getStatusLine().getReasonPhrase()
                        + " status code: " + statusCode;
            } else {
                HttpEntity entity = response.getEntity();

                if (entity != null && entity.getContentType().getValue().toLowerCase().contains("json")) {
                    ObjectMapper mapper = new ObjectMapper();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
                    Map<String, Object> userData = mapper.readValue(reader, Map.class);
                    // stuff the map in the Context...
                    for (Map.Entry<String, Object> e : userData.entrySet()) {
                        ctxt.putContext(e.getKey(), e.getValue());
                    }
                } else {
                    logger.error("unexpected body");
                    return "Error with Oauth2 token request - missing body";
                }
            }
        } catch (IOException e) {
            throw new IllegalArgumentException(e.toString());
        }
    }

    // OK if we got here, we have a valid token.  
    // Issue the request...
    String email = null;
    {
        URI nakedUri;
        try {
            nakedUri = new URI(userInfoUrl);
        } catch (URISyntaxException e2) {
            e2.printStackTrace();
            logger.error(e2.toString());
            return getSelfUrl();
        }

        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.add(new BasicNameValuePair("access_token", (String) ctxt.getContext("access_token")));
        URI uri;
        try {
            uri = URIUtils.createURI(nakedUri.getScheme(), nakedUri.getHost(), nakedUri.getPort(),
                    nakedUri.getPath(), URLEncodedUtils.format(qparams, "UTF-8"), null);
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
            logger.error(e1.toString());
            return getSelfUrl();
        }

        // DON'T NEED clientId on the toke request...
        // addCredentials(clientId, clientSecret, nakedUri.getHost());
        // setup request interceptor to do preemptive auth
        // ((DefaultHttpClient) client).addRequestInterceptor(getPreemptiveAuth(), 0);

        HttpClientFactory factory = new GaeHttpClientFactoryImpl();

        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS);
        HttpConnectionParams.setSoTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS);
        // support redirecting to handle http: => https: transition
        HttpClientParams.setRedirecting(httpParams, true);
        // support authenticating
        HttpClientParams.setAuthenticating(httpParams, true);

        httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 1);
        httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        // setup client
        HttpClient client = factory.createHttpClient(httpParams);

        HttpGet httpget = new HttpGet(uri);
        logger.info(httpget.getURI().toString());

        HttpResponse response = null;
        try {
            response = client.execute(httpget, localContext);
            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode != HttpStatus.SC_OK) {
                logger.error("not 200: " + statusCode);
                return "Error - reason: " + response.getStatusLine().getReasonPhrase() + " status code: "
                        + statusCode;
            } else {
                HttpEntity entity = response.getEntity();

                if (entity != null && entity.getContentType().getValue().toLowerCase().contains("json")) {
                    ObjectMapper mapper = new ObjectMapper();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
                    Map<String, Object> userData = mapper.readValue(reader, Map.class);

                    email = (String) userData.get("email");
                } else {
                    logger.error("unexpected body");
                    return "Error - missing body";
                }
            }
        } catch (IOException e) {
            throw new IllegalArgumentException(e.toString());
        }
    }

    return email;
}

From source file:illab.nabal.proxy.AbstractContext.java

/**
 * Get base string for HMAC-SHA1 encoding.
 * /*w  ww  .j  a  v  a 2  s  . co  m*/
 * @param httpMethod
 * @param baseUri
 * @param queryParams
 * @return baseString - composed baseString by OAuth 1.0a specification
 * @throws Exception
 */
protected String getBaseString(String httpMethod, String baseUri, List<NameValuePair> queryParams)
        throws Exception {
    /*
     *#################################################
     *  This algorithm(for OAuth 1.0a) is simply expressed in the pseudo-code :
     *#################################################
     *
     *          httpMethod + "&" +
     *          url_encode(  base_uri ) + "&" +
     *          sorted_query_params.each { | k, v |
     *              url_encode ( k ) + "%3D" +
     *              url_encode ( v )
     *          }.join("%26")
     *      
     *#################################################
     */
    String baseString = null;
    List<NameValuePair> sortedQueryParams = queryParams;

    if (StringHelper.isEmpty(httpMethod) == false && sortedQueryParams != null
            && sortedQueryParams.size() > 0) {

        // sort parameters using lexicographical byte value ordering
        sortedQueryParams = ParameterHelper.sortParams(sortedQueryParams);

        String paramQueryString = URLEncodedUtils.format(sortedQueryParams, UTF_8);

        //Log.d(TAG, "## BEFORE :: paramQueryString :\n" + paramQueryString);

        // replace '+' with '%20' to process POST parameter values with spaces
        paramQueryString = paramQueryString.replaceAll("\\+", "%20");

        // TODO error still occurs even though asterisks are all URL-encoded (2014-01-06)
        /*
        * Unauthorized {"errors":[{"message":"Could not authenticate you","code":32}]}
         */
        // replace '*' with '%2A' to process POST parameter values with asterisks
        paramQueryString = paramQueryString.replaceAll("\\*", "%2A");

        //Log.d(TAG, "## AFTER :: paramQueryString :\n" + paramQueryString);

        // compose a base string corresponding to method, host and URI path
        baseString = new StringHelper().appendAllToString(httpMethod, AMPERSEND,
                URLEncoder.encode(baseUri, UTF_8), AMPERSEND, URLEncoder.encode(paramQueryString, UTF_8));
    }
    return baseString;
}

From source file:tw.com.sti.store.api.android.AndroidApiService.java

/**
 * Check Pay Status(16): /* ww w. jav  a2  s . c o m*/
 */
public ApiInvoker<CheckPayStatusRet> checkPayStatus(String packageName, Integer lappv) {
    String url = apiUrl.getCheckPayStatusUrl(packageName);
    ApiDataParseHandler<CheckPayStatusRet> handler = ApiDataParseHandler.CHECK_PAY_STATUS_RET_PARSE_HANDLER;
    List<NameValuePair> nvps = createRequestParams();
    if (Logger.DEBUG) {
        L.d(url + "?" + URLEncodedUtils.format(nvps, "UTF-8"));
    }
    return new ApiInvoker<CheckPayStatusRet>(this.config, handler, url, nvps);
}

From source file:tw.com.sti.store.api.android.AndroidApiService.java

/**
 * Unsubscribe(17): ?//from   w  ww  .  j av  a 2s.c o m
 */
public ApiInvoker<UnsubscribeRet> unsubscribe(String packageName) {
    String url = apiUrl.getUnsubscribeUrl(packageName);
    ApiDataParseHandler<UnsubscribeRet> handler = ApiDataParseHandler.UNSUBSCRIBE_RET_PARSE_HANDLER;
    List<NameValuePair> nvps = createRequestParams();
    if (Logger.DEBUG) {
        L.d(url + "?" + URLEncodedUtils.format(nvps, "UTF-8"));
    }
    return new ApiInvoker<UnsubscribeRet>(this.config, handler, url, nvps);
}

From source file:com.senseidb.svc.impl.HttpRestSenseiServiceImpl.java

public URI buildRequestURI(List<NameValuePair> qparams) throws URISyntaxException {
    URI uri = URIUtils.createURI(_scheme, _host, _port, _path, URLEncodedUtils.format(qparams, "UTF-8"), null);
    return uri;/*from   w ww. ja  va  2 s .  c o m*/
}

From source file:org.dvbviewer.controller.ui.fragments.ChannelList.java

public boolean onContextItemSelected(MenuItem item) {
    if (item.getMenuInfo() != null) {
        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
        selectedPosition = info.position;
    }/*from   ww  w  .  j  ava 2 s .  c o m*/
    Cursor c = mAdapter.getCursor();
    c.moveToPosition(selectedPosition);
    Channel chan = cursorToChannel(c);
    Timer timer;
    switch (item.getItemId()) {
    case R.id.menuTimer:
        timer = cursorToTimer(c);
        if (UIUtils.isTablet(getActivity())) {
            TimerDetails timerdetails = TimerDetails.newInstance();
            Bundle args = new Bundle();
            args.putString(TimerDetails.EXTRA_TITLE, timer.getTitle());
            args.putString(TimerDetails.EXTRA_CHANNEL_NAME, timer.getChannelName());
            args.putLong(TimerDetails.EXTRA_CHANNEL_ID, timer.getChannelId());
            args.putLong(TimerDetails.EXTRA_START, timer.getStart().getTime());
            args.putLong(TimerDetails.EXTRA_END, timer.getEnd().getTime());
            timerdetails.setArguments(args);
            timerdetails.show(getSherlockActivity().getSupportFragmentManager(), TimerDetails.class.getName());
        } else {
            Intent timerIntent = new Intent(getActivity(), TimerDetailsActivity.class);
            timerIntent.putExtra(TimerDetails.EXTRA_TITLE, timer.getTitle());
            timerIntent.putExtra(TimerDetails.EXTRA_CHANNEL_NAME, timer.getChannelName());
            timerIntent.putExtra(TimerDetails.EXTRA_CHANNEL_ID, timer.getChannelId());
            timerIntent.putExtra(TimerDetails.EXTRA_START, timer.getStart().getTime());
            timerIntent.putExtra(TimerDetails.EXTRA_END, timer.getEnd().getTime());
            startActivity(timerIntent);
        }
        return true;
    case R.id.menuStream:
        if (UIUtils.isTablet(getActivity())) {
            StreamConfig cfg = StreamConfig.newInstance();
            Bundle arguments = new Bundle();
            arguments.putInt(StreamConfig.EXTRA_FILE_ID, chan.getPosition());
            arguments.putInt(StreamConfig.EXTRA_FILE_TYPE, StreamConfig.FILE_TYPE_LIVE);
            arguments.putInt(StreamConfig.EXTRA_DIALOG_TITLE_RES, R.string.streamConfig);
            cfg.setArguments(arguments);
            cfg.show(getSherlockActivity().getSupportFragmentManager(), StreamConfig.class.getName());
        } else {
            Intent streamConfig = new Intent(getActivity(), StreamConfigActivity.class);
            streamConfig.putExtra(StreamConfig.EXTRA_FILE_ID, chan.getPosition());
            streamConfig.putExtra(StreamConfig.EXTRA_FILE_TYPE, StreamConfig.FILE_TYPE_LIVE);
            streamConfig.putExtra(StreamConfig.EXTRA_DIALOG_TITLE_RES, R.string.streamConfig);
            startActivity(streamConfig);
        }
        return true;
    case R.id.menuSwitch:
        String switchRequest = ServerConsts.URL_SWITCH_COMMAND + chan.getPosition();
        DVBViewerCommand command = new DVBViewerCommand(switchRequest);
        Thread exexuterTHread = new Thread(command);
        exexuterTHread.start();
        return true;
    case R.id.menuRecord:
        timer = cursorToTimer(c);
        String url = timer.getId() <= 0l ? ServerConsts.URL_TIMER_CREATE : ServerConsts.URL_TIMER_EDIT;
        String title = timer.getTitle();
        String days = String.valueOf(DateUtils.getDaysSinceDelphiNull(timer.getStart()));
        String start = String.valueOf(DateUtils.getMinutesOfDay(timer.getStart()));
        String stop = String.valueOf(DateUtils.getMinutesOfDay(timer.getEnd()));
        String endAction = String.valueOf(timer.getTimerAction());
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("ch", String.valueOf(timer.getChannelId())));
        params.add(new BasicNameValuePair("dor", days));
        params.add(new BasicNameValuePair("encoding", "255"));
        params.add(new BasicNameValuePair("enable", "1"));
        params.add(new BasicNameValuePair("start", start));
        params.add(new BasicNameValuePair("stop", stop));
        params.add(new BasicNameValuePair("title", title));
        params.add(new BasicNameValuePair("endact", endAction));
        if (timer.getId() > 0) {
            params.add(new BasicNameValuePair("id", String.valueOf(timer.getId())));
        }

        String query = URLEncodedUtils.format(params, "utf-8");
        String request = url + query;
        RecordingServiceGet rsGet = new RecordingServiceGet(request);
        Thread executionThread = new Thread(rsGet);
        executionThread.start();
        return true;

    default:
        break;
    }
    return false;
}

From source file:tw.com.sti.store.api.android.AndroidApiService.java

/**
 * Check New Client(18): Client/*from   w ww  . j a va  2s.c o  m*/
 */
public ApiInvoker<CheckClientVersionRet> checkClientVersion(String msisdn) {
    String url = apiUrl.getCheckNewClientUrl();
    ApiDataParseHandler<CheckClientVersionRet> handler = ApiDataParseHandler.CHECK_CLIENT_VERSION_HANDLER;
    String[] paramNames = new String[] { "msisdn" };
    if (msisdn == null)
        msisdn = "";
    String[] paramValues = new String[] { msisdn };
    List<NameValuePair> nvps = createRequestParams(paramNames, paramValues, true);
    if (Logger.DEBUG) {
        L.d(url + "?" + URLEncodedUtils.format(nvps, "UTF-8"));
    }
    ApiInvoker<CheckClientVersionRet> apiInvoker = new ApiInvoker<CheckClientVersionRet>(this.config, handler,
            url, nvps);
    return apiInvoker;
}