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:com.lgallardo.qbittorrentclient.JSONParser.java

public String postCommand(String command, String hash) throws JSONParserStatusCodeException {

    String key = "hash";

    String urlContentType = "application/x-www-form-urlencoded";

    String limit = "";
    String tracker = "";

    String boundary = null;// w  w w  .j  av  a  2s  . c o  m

    String fileId = "";

    String filePriority = "";

    String result = "";

    StringBuilder fileContent = null;

    HttpResponse httpResponse;
    DefaultHttpClient httpclient;

    String url = "";

    String label = "";

    if ("start".equals(command) || "startSelected".equals(command)) {
        url = "command/resume";
    }

    if ("pause".equals(command) || "pauseSelected".equals(command)) {
        url = "command/pause";
    }

    if ("delete".equals(command) || "deleteSelected".equals(command)) {
        url = "command/delete";
        key = "hashes";
    }

    if ("deleteDrive".equals(command) || "deleteDriveSelected".equals(command)) {
        url = "command/deletePerm";
        key = "hashes";
    }

    if ("addTorrent".equals(command)) {
        url = "command/download";
        key = "urls";
    }

    if ("addTracker".equals(command)) {
        url = "command/addTrackers";
        key = "hash";

    }

    if ("addTorrentFile".equals(command)) {
        url = "command/upload";
        key = "urls";

        boundary = "-----------------------" + (new Date()).getTime();

        urlContentType = "multipart/form-data; boundary=" + boundary;

    }

    if ("pauseall".equals(command)) {
        url = "command/pauseall";
    }

    if ("pauseAll".equals(command)) {
        url = "command/pauseAll";
    }

    if ("resumeall".equals(command)) {
        url = "command/resumeall";
    }

    if ("resumeAll".equals(command)) {
        url = "command/resumeAll";
    }

    if ("increasePrio".equals(command)) {
        url = "command/increasePrio";
        key = "hashes";
    }

    if ("decreasePrio".equals(command)) {
        url = "command/decreasePrio";
        key = "hashes";

    }

    if ("maxPrio".equals(command)) {
        url = "command/topPrio";
        key = "hashes";
    }

    if ("minPrio".equals(command)) {
        url = "command/bottomPrio";
        key = "hashes";

    }

    if ("setFilePrio".equals(command)) {
        url = "command/setFilePrio";

        String[] tmpString = hash.split("&");
        hash = tmpString[0];
        fileId = tmpString[1];
        filePriority = tmpString[2];

        //            Log.d("Debug", "hash: " + hash);
        //            Log.d("Debug", "fileId: " + fileId);
        //            Log.d("Debug", "filePriority: " + filePriority);
    }

    if ("setQBittorrentPrefefrences".equals(command)) {
        url = "command/setPreferences";
        key = "json";
    }

    if ("setUploadRateLimit".equals(command)) {

        url = "command/setTorrentsUpLimit";
        key = "hashes";

        String[] tmpString = hash.split("&");
        hash = tmpString[0];

        try {
            limit = tmpString[1];
        } catch (ArrayIndexOutOfBoundsException e) {
            limit = "-1";
        }
    }

    if ("setDownloadRateLimit".equals(command)) {
        url = "command/setTorrentsDlLimit";
        key = "hashes";

        Log.d("Debug", "Hash before: " + hash);

        String[] tmpString = hash.split("&");
        hash = tmpString[0];

        try {
            limit = tmpString[1];
        } catch (ArrayIndexOutOfBoundsException e) {
            limit = "-1";
        }

        //            Log.d("Debug", "url: " + url);
        //            Log.d("Debug", "Hashes: " + hash + " | limit: " + limit);

    }

    if ("recheckSelected".equals(command)) {
        url = "command/recheck";
    }

    if ("toggleFirstLastPiecePrio".equals(command)) {
        url = "command/toggleFirstLastPiecePrio";
        key = "hashes";

    }

    if ("toggleSequentialDownload".equals(command)) {
        url = "command/toggleSequentialDownload";
        key = "hashes";

    }

    if ("toggleAlternativeSpeedLimits".equals(command)) {

        //            Log.d("Debug", "Toggling alternative rates");

        url = "command/toggleAlternativeSpeedLimits";
        key = "hashes";

    }

    if ("setLabel".equals(command)) {
        url = "command/setLabel";
        key = "hashes";

        String[] tmpString = hash.split("&");
        hash = tmpString[0];

        try {
            label = tmpString[1];
        } catch (ArrayIndexOutOfBoundsException e) {
            label = "";
        }

        //            Log.d("Debug", "Hash2: " + hash + "| label2: " + label);

    }

    if ("setCategory".equals(command)) {
        url = "command/setCategory";
        key = "hashes";

        String[] tmpString = hash.split("&");
        hash = tmpString[0];

        try {
            label = tmpString[1];
        } catch (ArrayIndexOutOfBoundsException e) {
            label = "";
        }

        //            Log.d("Debug", "Hash2: " + hash + "| label2: " + label);

    }

    if ("alternativeSpeedLimitsEnabled".equals(command)) {

        //            Log.d("Debug", "Getting alternativeSpeedLimitsEnabled");

        url = "command/alternativeSpeedLimitsEnabled";

        key = "hashes";
    }

    // if server is publish in a subfolder, fix url
    if (subfolder != null && !subfolder.equals("")) {
        url = subfolder + "/" + url;
    }

    HttpParams httpParameters = new BasicHttpParams();

    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    int timeoutConnection = connection_timeout * 1000;

    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = data_timeout * 1000;

    // Set http parameters
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    HttpProtocolParams.setUserAgent(httpParameters, "qBittorrent for Android");
    HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);

    // Making HTTP request
    HttpHost targetHost = new HttpHost(this.hostname, this.port, this.protocol);

    // httpclient = new DefaultHttpClient();
    httpclient = getNewHttpClient();

    httpclient.setParams(httpParameters);

    try {

        AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());

        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password);

        httpclient.getCredentialsProvider().setCredentials(authScope, credentials);

        url = protocol + "://" + hostname + ":" + port + "/" + url;

        HttpPost httpget = new HttpPost(url);

        if ("addTorrent".equals(command)) {

            URI hash_uri = new URI(hash);
            hash = hash_uri.toString();
        }

        if ("addTracker".equals(command)) {

            String[] tmpString = hash.split("&");
            hash = tmpString[0];

            URI hash_uri = new URI(hash);
            hash = hash_uri.toString();

            try {
                tracker = tmpString[1];
            } catch (ArrayIndexOutOfBoundsException e) {
                tracker = "";
            }

            //                Log.d("Debug", "addTracker - hash: " + hash);
            //                Log.d("Debug", "addTracker - tracker: " + tracker);

        }

        // In order to pass the hash we must set the pair name value
        BasicNameValuePair bnvp = new BasicNameValuePair(key, hash);

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(bnvp);

        // Add limit
        if (!limit.equals("")) {
            Log.d("Debug", "JSONParser - Limit: " + limit);
            nvps.add(new BasicNameValuePair("limit", limit));
        }

        // Set values for setting file priority
        if ("setFilePrio".equals(command)) {

            nvps.add(new BasicNameValuePair("id", fileId));
            nvps.add(new BasicNameValuePair("priority", filePriority));
        }

        // Add label
        if (label != null && !label.equals("")) {

            label = Uri.decode(label);

            if ("setLabel".equals(command)) {

                nvps.add(new BasicNameValuePair("label", label));
            } else {

                nvps.add(new BasicNameValuePair("category", label));
            }

            //                Log.d("Debug", "Hash3: " + hash + "| label3: >" + label + "<");
        }

        // Add tracker
        if (tracker != null && !tracker.equals("")) {

            nvps.add(new BasicNameValuePair("urls", tracker));

            //                Log.d("Debug", ">Tracker: " + key + " | " + hash + " | " + tracker + "<");

        }

        String entityValue = URLEncodedUtils.format(nvps, HTTP.UTF_8);

        // This replaces encoded char "+" for "%20" so spaces can be passed as parameter
        entityValue = entityValue.replaceAll("\\+", "%20");

        StringEntity stringEntity = new StringEntity(entityValue, HTTP.UTF_8);
        stringEntity.setContentType(URLEncodedUtils.CONTENT_TYPE);

        httpget.setEntity(stringEntity);

        // Set content type and urls
        if ("addTorrent".equals(command) || "increasePrio".equals(command) || "decreasePrio".equals(command)
                || "maxPrio".equals(command) || "setFilePrio".equals(command)
                || "toggleAlternativeSpeedLimits".equals(command)
                || "alternativeSpeedLimitsEnabled".equals(command) || "setLabel".equals(command)
                || "setCategory".equals(command) || "addTracker".equals(command)) {
            httpget.setHeader("Content-Type", urlContentType);
        }

        // Set cookie
        if (this.cookie != null) {
            httpget.setHeader("Cookie", this.cookie);
        }

        // Set content type and urls
        if ("addTorrentFile".equals(command)) {

            httpget.setHeader("Content-Type", urlContentType);

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

            // Add boundary
            builder.setBoundary(boundary);

            // Add torrent file as binary
            File file = new File(hash);
            // FileBody fileBody = new FileBody(file);
            // builder.addPart("file", fileBody);

            builder.addBinaryBody("upfile", file, ContentType.DEFAULT_BINARY, hash);

            // Build entity
            HttpEntity entity = builder.build();

            // Set entity to http post
            httpget.setEntity(entity);

        }

        httpResponse = httpclient.execute(targetHost, httpget);

        StatusLine statusLine = httpResponse.getStatusLine();

        int mStatusCode = statusLine.getStatusCode();

        //            Log.d("Debug", "JSONPArser - mStatusCode: " + mStatusCode);

        if (mStatusCode != 200) {
            httpclient.getConnectionManager().shutdown();
            throw new JSONParserStatusCodeException(mStatusCode);
        }

        HttpEntity httpEntity = httpResponse.getEntity();

        result = EntityUtils.toString(httpEntity);

        //            Log.d("Debug", "JSONPArser - command result: " + result);

        return result;

    } catch (UnsupportedEncodingException e) {

    } catch (ClientProtocolException e) {
        Log.e("Debug", "Client: " + e.toString());
        e.printStackTrace();
    } catch (SSLPeerUnverifiedException e) {
        Log.e("JSON", "SSLPeerUnverifiedException: " + e.toString());
        throw new JSONParserStatusCodeException(NO_PEER_CERTIFICATE);
    } catch (IOException e) {
        Log.e("Debug", "IO: " + e.toString());
        httpclient.getConnectionManager().shutdown();
        throw new JSONParserStatusCodeException(TIMEOUT_ERROR);
    } catch (JSONParserStatusCodeException e) {
        httpclient.getConnectionManager().shutdown();
        throw new JSONParserStatusCodeException(e.getCode());
    } catch (Exception e) {
        Log.e("Debug", "Generic: " + e.toString());
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

    return null;

}

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

private void updateZoomedBytes() throws BAGException {
    HttpGet getReq = null;/*  w  ww .ja  v a 2s . c  o  m*/
    try {

        ArrayList<NameValuePair> reqParams = (ArrayList<NameValuePair>) this.djatokaParams.clone();

        // Curiously the X and Y coordinates need not be scaled using the level scale ratio
        // long djatokaY = Math.round(this.zoomedY * this.djatokaLevelScaleRatio);
        // long djatokaX = Math.round(this.zoomedX * this.djatokaLevelScaleRatio);

        long djatokaWidth = Math.round(
                (this.zoomedWidth > 0 ? this.zoomedWidth : this.fullWidth) * this.djatokaLevelScaleRatio);

        // make use of view pane height to minimize retrieved image
        if (this.zoomedWidth == this.fullWidth) {
            this.zoomedHeight = this.fullHeight; // To allow the retrieval of the full image
        } else {
            double zoomedPixelRatio = (double) this.zoomedWidth / this.viewPaneWidth;
            if (Math.abs(
                    Math.round((double) this.zoomedHeight / zoomedPixelRatio) - this.viewPaneHeight) > 10) {
                this.zoomedHeight = Math.round(this.viewPaneHeight * zoomedPixelRatio);
            }
        }

        long djatokaHeight = Math.round(
                (this.zoomedHeight > 0 ? this.zoomedHeight : this.fullHeight) * this.djatokaLevelScaleRatio);

        reqParams.add(new BasicNameValuePair("svc.rotate", "" + this.zoomedRotate));

        reqParams.add(new BasicNameValuePair("svc.scale",
                "" + Math.round(this.viewPaneWidth * this.scaleFactor) + ",0"));
        reqParams.add(new BasicNameValuePair("svc.level", "" + this.djatokaLevel));
        reqParams.add(new BasicNameValuePair("svc.region",
                // "" + djatokaY + "," + djatokaX + ","
                "" + this.zoomedY + "," + this.zoomedX + "," + djatokaHeight + "," + djatokaWidth));

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

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

        getReq = new HttpGet(reqUri);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Getting region via URL: " + getReq.getURI());
        }

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

        if (LOG.isDebugEnabled()) {
            LOG.debug("Response from URL: " + getReq.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 ("image/jpeg".equalsIgnoreCase(entity.getContentType().getValue())) {
                this.zoomedBytes = EntityUtils.toByteArray(entity);
            }
        } else {

            throw new BAGException("Cannot retrieve region!");
        }

    } 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.
        getReq.abort();
        throw ex;

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

}

From source file:net.mypapit.mobile.myrepeater.DisplayMap.java

/**
 * Making service call/*from  ww w .  j  a  va 2s  .c om*/
 * 
 * @url - url to make request
 * @method - http request method
 * @params - http request params
 * */
public String makeServiceCall(String url, int method, List<NameValuePair> params) {
    try {
        // http client
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;

        // Checking http request method type
        if (method == POST) {
            HttpPost httpPost = new HttpPost(url);
            // adding post params
            if (params != null) {
                httpPost.setEntity(new UrlEncodedFormEntity(params));
            }

            httpResponse = httpClient.execute(httpPost);

        } else if (method == GET) {
            // appending params to url
            if (params != null) {
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
            }
            HttpGet httpGet = new HttpGet(url);

            httpResponse = httpClient.execute(httpGet);

        }
        httpEntity = httpResponse.getEntity();
        response = EntityUtils.toString(httpEntity);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return response;

}

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

/**
 * My Download ( Free, Paid, All )(13): App ?Free, InApp, InApp
 * , , InApp/*  ww w .ja v  a  2  s  .co  m*/
 */
public ApiInvoker<AppsRet> myDownloadApps(AppsType appsType, int page) {
    String url = apiUrl.getMyDownloadAppsUrl(appsType, page);
    ApiDataParseHandler<AppsRet> handler = ApiDataParseHandler.APPS_RET_PARSE_HANDLER;
    List<NameValuePair> nvps = createRequestParams();
    if (Logger.DEBUG) {
        L.d(url + "?" + URLEncodedUtils.format(nvps, "UTF-8"));
    }
    return new ApiInvoker<AppsRet>(this.config, handler, url, nvps);
}

From source file:dataServer.StorageRESTClientManager.java

public String getProductProperties(String productId) {
    // Default HTTP client and common properties for requests
    requestUrl = null;//w ww  . j  av  a  2 s .  c o  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 product properties
    requestUrl = new StringBuilder("http://" + storageLocation + ":" + storagePortRegistryC
            + storageRegistryContext + "/query/product/properties");

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

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

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

/**
 * Send Client Usage Log (14): Client //  w  w  w  .j  a v a 2  s. c  om
 */
public ApiInvoker<CommonRet> clientUsage(String l_uid, String l_userId, String l_iccid, String l_imei,
        String l_cver, long l_time, String l_dvc, String l_imsi, String l_msisdn, String l_isFirstTime) {
    String[] paramNames = new String[] { "l_uid", "l_userId", "l_iccid", "l_imei", "l_cver", "l_time", "l_dvc",
            "l_imsi", "l_msisdn", "l_isFirstTime" };
    String[] paramValues = new String[] { l_uid, l_userId, l_iccid, l_imei, l_cver, String.valueOf(l_time),
            l_dvc, l_imsi, l_msisdn, l_isFirstTime };
    String url = apiUrl.getClientUsageUrl();
    ApiDataParseHandler<CommonRet> handler = ApiDataParseHandler.COMMON_RET_PARSE_HANDLER;
    List<NameValuePair> nvps = createRequestParams(paramNames, paramValues, true);
    if (Logger.DEBUG) {
        L.d(url + "?" + URLEncodedUtils.format(nvps, "UTF-8"));
    }
    return new ApiInvoker<CommonRet>(this.config, handler, url, nvps);
}

From source file:edu.jhu.pha.vospace.storage.SwiftKeystoneStorageManager.java

private static String makeURI(String base, List<NameValuePair> parameters) {
    return base + "?" + URLEncodedUtils.format(parameters, "UTF-8");
}

From source file:cn.com.loopj.android.http.RequestParams.java

protected String getParamString() {
    return URLEncodedUtils.format(getParamsList(), contentEncoding);
}

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

@Override
public ProlongAllResult prolongAll(Account account, int useraction, String selection) throws IOException {
    Document doc = getAccountPage(account);
    // Check if the iOPAC verion supports this feature
    if (doc.select("button.verlallbutton").size() > 0) {
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("mode", "42"));
        for (Element checkbox : doc.select("input.VerlAllCheckboxOK")) {
            params.add(new BasicNameValuePair("MedNrVerlAll", checkbox.val()));
        }//from   w  w  w  .  ja  v a 2  s .  com
        String html = httpGet(opac_url + "/cgi-bin/di.exe?" + URLEncodedUtils.format(params, "UTF-8"),
                getDefaultEncoding());
        Document doc2 = Jsoup.parse(html);
        Pattern pattern = Pattern.compile("(\\d+ Medi(?:en|um) wurden? verl.ngert)\\s*(\\d+ "
                + "Medi(?:en|um) wurden? nicht verl.ngert)?");
        Matcher matcher = pattern.matcher(doc2.text());
        if (matcher.find()) {
            String text1 = matcher.group(1);
            String text2 = matcher.group(2);
            List<Map<String, String>> list = new ArrayList<>();
            Map<String, String> map1 = new HashMap<>();
            // TODO: We are abusing the ProlongAllResult.KEY_LINE_ ... keys here because we
            // do not get information about all the media
            map1.put(ProlongAllResult.KEY_LINE_TITLE, text1);
            list.add(map1);
            if (text2 != null && !text2.equals("")) {
                Map<String, String> map2 = new HashMap<>();
                map2.put(ProlongAllResult.KEY_LINE_TITLE, text2);
                list.add(map2);
            }
            return new ProlongAllResult(MultiStepResult.Status.OK, list);
        } else {
            return new ProlongAllResult(MultiStepResult.Status.ERROR, doc2.text());
        }
    } else {
        return new ProlongAllResult(MultiStepResult.Status.ERROR,
                stringProvider.getString(StringProvider.UNSUPPORTED_IN_LIBRARY));
    }
}

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

/**
 * Is Over Payment Quota?(15): ???//from w  ww.  j  ava  2  s  . com
 */
public ApiInvoker<OverPaymentQuotaRet> overPaymentQuota(String packageName) {
    String url = apiUrl.getOverPaymentQuotaUrl(packageName);
    ApiDataParseHandler<OverPaymentQuotaRet> handler = ApiDataParseHandler.OVER_PAYMENT_QUOTA_RET_PARSE_HANDLER;
    List<NameValuePair> nvps = createRequestParams();
    if (Logger.DEBUG) {
        L.d(url + "?" + URLEncodedUtils.format(nvps, "UTF-8"));
    }
    return new ApiInvoker<OverPaymentQuotaRet>(this.config, handler, url, nvps);
}