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:tw.com.sti.store.api.android.AndroidApiService.java

/**
 * Check My Apps Version(20): App/*  w  w w.j av a2s .  c o m*/
 */
public ApiInvoker<AppVersionsRet> myAppVersions(String msisdn, int page) {
    String url = apiUrl.getMyAppsVersionUrl(page);
    ApiDataParseHandler<AppVersionsRet> handler = ApiDataParseHandler.MY_APP_VERSIONS_PARSE_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"));
    }
    return new ApiInvoker<AppVersionsRet>(this.config, handler, url, nvps);
}

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

/**
 * Download App(21):  App/*from   w w  w.  j a  v a 2  s.  c om*/
 */
public HttpRequestBase downloadApp(String packageName, String categoryId, Integer lappv, String vlogId)
        throws UnsupportedEncodingException {
    if (config.getServerType() == Configuration.RUNTIME_SERVER_TYPE.STAGING) {
        if (LangUtils.isBlank(categoryId) || "0".equals(categoryId))
            throw new RuntimeException("categoryId invalid: " + categoryId);
    }
    String url = apiUrl.getDownloadAppUrl(packageName);
    List<NameValuePair> nvps;
    String[] paramNames;
    String[] paramValues;
    if (lappv != null) {
        if (LangUtils.isBlank(vlogId)) {
            paramNames = new String[] { "categoryId", "lappv" };
            paramValues = new String[] { categoryId, lappv.toString() };
        } else {
            paramNames = new String[] { "categoryId", "lappv", "vlogId" };
            paramValues = new String[] { categoryId, lappv.toString(), vlogId };
        }
    } else {
        if (LangUtils.isBlank(vlogId)) {
            paramNames = new String[] { "categoryId" };
            paramValues = new String[] { categoryId };
        } else {
            paramNames = new String[] { "categoryId", "vlogId" };
            paramValues = new String[] { categoryId, vlogId };
        }
    }

    nvps = createRequestParams(paramNames, paramValues, true);
    if (Logger.DEBUG) {
        L.d(url + "?" + URLEncodedUtils.format(nvps, "UTF-8"));
    }
    HttpPost post = new HttpPost(url);
    post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
    return post;
}

From source file:com.tremolosecurity.unison.openstack.KeystoneProvisioningTarget.java

public UserAndID lookupUser(String userID, Set<String> attributes, Map<String, Object> request, KSToken token,
        HttpCon con) throws Exception {

    KSUser fromKS = null;//  w  w w .ja va 2 s  .  co m

    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("domain_id", this.usersDomain));
    qparams.add(new BasicNameValuePair("name", userID));

    StringBuffer b = new StringBuffer();
    b.append(this.url).append("/users?").append(URLEncodedUtils.format(qparams, "UTF-8"));
    String fullURL = b.toString();
    String json = this.callWS(token.getAuthToken(), con, fullURL);

    Gson gson = new Gson();
    UserLookupResponse resp = gson.fromJson(json, UserLookupResponse.class);

    if (resp.getUsers().isEmpty()) {
        return null;
    } else {
        fromKS = resp.getUsers().get(0);

        User user = new User(fromKS.getName());

        if (attributes.contains("name")) {
            user.getAttribs().put("name", new Attribute("name", fromKS.getName()));
        }

        if (attributes.contains("id")) {
            user.getAttribs().put("id", new Attribute("id", fromKS.getId()));
        }

        if (attributes.contains("email") && fromKS.getEmail() != null) {
            user.getAttribs().put("email", new Attribute("email", fromKS.getEmail()));
        }

        if (attributes.contains("description") && fromKS.getDescription() != null) {
            user.getAttribs().put("description", new Attribute("description", fromKS.getEmail()));
        }

        if (attributes.contains("enabled")) {
            user.getAttribs().put("enabled", new Attribute("enabled", Boolean.toString(fromKS.getEnabled())));
        }

        if (!rolesOnly) {
            b.setLength(0);
            b.append(this.url).append("/users/").append(fromKS.getId()).append("/groups");
            json = this.callWS(token.getAuthToken(), con, b.toString());

            GroupLookupResponse gresp = gson.fromJson(json, GroupLookupResponse.class);

            for (KSGroup group : gresp.getGroups()) {
                user.getGroups().add(group.getName());
            }
        }

        if (attributes.contains("roles")) {
            b.setLength(0);
            b.append(this.url).append("/role_assignments?user.id=").append(fromKS.getId())
                    .append("&include_names=true");
            json = this.callWS(token.getAuthToken(), con, b.toString());

            RoleAssignmentResponse rar = gson.fromJson(json, RoleAssignmentResponse.class);
            Attribute attr = new Attribute("roles");
            for (KSRoleAssignment role : rar.getRole_assignments()) {
                if (role.getScope().getProject() != null) {
                    attr.getValues()
                            .add(gson.toJson(new Role(role.getRole().getName(), "project",
                                    role.getScope().getProject().getDomain().getName(),
                                    role.getScope().getProject().getName())));
                } else {
                    attr.getValues().add(gson.toJson(new Role(role.getRole().getName(), "domain",
                            role.getScope().getDomain().getName())));
                }
            }

            if (!attr.getValues().isEmpty()) {
                user.getAttribs().put("roles", attr);
            }

        }

        UserAndID userAndId = new UserAndID();
        userAndId.setUser(user);
        userAndId.setId(fromKS.getId());

        return userAndId;
    }

}

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

/**
 * ? API 13: ?//from w  w w  . jav a 2 s  .  c o  m
 */
public ApiInvoker<LicenseInfoRet> getLicense(String packageName, Integer lappv) {
    String[] paramNames = new String[] { "ver" };
    String[] paramValues = new String[] { "" + lappv };
    String url = apiUrl.getLicenseUrl(packageName);
    ApiDataParseHandler<LicenseInfoRet> handler = ApiDataParseHandler.LICENSE_RET_PARSE_HANDLER;
    List<NameValuePair> nvps = createRequestParams(paramNames, paramValues, true);
    if (Logger.DEBUG) {
        L.d(url + "?" + URLEncodedUtils.format(nvps, "UTF-8"));
    }
    return new ApiInvoker<LicenseInfoRet>(this.config, handler, url, nvps);
}

From source file:org.urbanstew.soundcloudapi.SoundCloudAPI.java

private String urlEncode(String resource, List<NameValuePair> params) {
    String resourceUrl;//  ww  w .ja  va2  s  .  c  o  m
    if (resource.startsWith("/"))
        resourceUrl = mSoundCloudApiURL + resource.substring(1);
    else
        resourceUrl = resource.contains("://") ? resource : mSoundCloudApiURL + resource;
    return params == null ? resourceUrl : resourceUrl + "?" + URLEncodedUtils.format(params, "UTF-8");
}

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

public ApiInvoker<OrderRet> getNewOrder(String packageName, String storeOid, String payeeInfo,
        UPayConfig uPayConfig) {//from  w  w  w. j  a  v  a2s .  co m
    String[] paramNames;
    String[] paramValues;
    if (uPayConfig == null) {
        paramNames = new String[] { "storeOid", "payeeInfo" };
        paramValues = new String[] { storeOid, payeeInfo };
    } else {
        paramNames = new String[] { "storeOid", "payeeInfo", "isTest", "checkSignUrl", "merchantId",
                "merchantName", "merchantPublicCer", "privateKeyFileName", "privateKeyAlias",
                "privateKeyPassword", "transTimeout", "backEndUrl" };
        paramValues = new String[] { storeOid, payeeInfo, uPayConfig.getIsTest(), uPayConfig.getCheckSignUrl(),
                uPayConfig.getMerchantId(), uPayConfig.getMerchantName(), uPayConfig.getMerchantPublicCer(),
                uPayConfig.getPrivateKeyFileName(), uPayConfig.getPrivateKeyAlias(),
                uPayConfig.getPrivateKeyPassword(), uPayConfig.getTransTimeout(), uPayConfig.getBackEndUrl() };
    }

    String url = apiUrl.getPaymentOrderNumtUrl(packageName);
    ApiDataParseHandler<OrderRet> handler = ApiDataParseHandler.G_PAYMENT_RET_PARSE_HANDLER;
    List<NameValuePair> nvps = createRequestParams(paramNames, paramValues, true);
    if (Logger.DEBUG) {
        L.d(url + "?" + URLEncodedUtils.format(nvps, "UTF-8"));
    }
    return new ApiInvoker<OrderRet>(this.config, handler, url, nvps);

}

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

/**
  * Get HTTP GET object.//from w w w .jav  a  2s. c om
 * 
 * @param apiUri
 * @param params
 * @return HttpGet
 * @throws Exception
 */
protected synchronized HttpGet getHttpGet(String apiUri, List<NameValuePair> params) throws Exception {

    // URL-encode GET parameters
    String paramString = "";
    if (params != null && params.size() > 0) {
        paramString = "?" + URLEncodedUtils.format(params, UTF_8);
    }

    return new HttpGet(new URI(getApiHost() + apiUri + paramString));
}

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

@Override
public String getShareUrl(String id, String title) {
    List<NameValuePair> params = new ArrayList<NameValuePair>();

    params.add(new BasicNameValuePair("Style", "Portal3"));
    params.add(new BasicNameValuePair("SubStyle", ""));
    params.add(new BasicNameValuePair("Lang", "GER"));
    params.add(new BasicNameValuePair("ResponseEncoding", "utf-8"));
    params.add(new BasicNameValuePair("no", id));

    return opac_url + "/APS_PRESENT_BIB?" + URLEncodedUtils.format(params, "UTF-8");
}

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

@Override
public String obtainOauth2Data(String destinationUrl) throws IllegalArgumentException {

    // get the auth code...
    Context ctxt = getStateContext(ctxtKey);
    String code = (String) ctxt.getContext("code");
    {// w w w  . j ava 2 s  .  com
        // 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 - unexpected body";
                }
            }
        } catch (IOException e) {
            throw new IllegalArgumentException(e.toString());
        }
    }

    // OK if we got here, we have a valid token.  
    // Issue the request...
    {
        URI nakedUri;
        try {
            nakedUri = new URI(destinationUrl);
        } 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";
            } else {
                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    String contentType = entity.getContentType().getValue();
                    if (contentType.toLowerCase().contains("xml")) {
                        BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
                        StringBuilder b = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            b.append(line);
                        }
                        String value = b.toString();
                        return value;
                    } else {
                        logger.error("unexpected body");
                        return "Error";
                    }
                } else {
                    logger.error("unexpected missing body");
                    return "Error";
                }
            }
        } catch (IOException e) {
            throw new IllegalArgumentException(e.toString());
        }
    }
}