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

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

Introduction

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

Prototype

String CONTENT_TYPE

To view the source code for org.apache.http.client.utils URLEncodedUtils CONTENT_TYPE.

Click Source Link

Document

The default HTML form content type.

Usage

From source file:com.adeven.adjustio.RequestHandler.java

private HttpUriRequest getRequest(ActivityPackage activityPackage) throws UnsupportedEncodingException {
    String url = Constants.BASE_URL + activityPackage.getPath();
    HttpPost request = new HttpPost(url);

    String language = Locale.getDefault().getLanguage();
    request.addHeader("User-Agent", activityPackage.getUserAgent());
    request.addHeader("Client-Sdk", activityPackage.getClientSdk());
    request.addHeader("Accept-Language", language);

    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    for (Map.Entry<String, String> entity : activityPackage.getParameters().entrySet()) {
        NameValuePair pair = new BasicNameValuePair(entity.getKey(), entity.getValue());
        pairs.add(pair);/*from  w w  w . j a v  a 2 s.c  om*/
    }

    Map<String, String> deviceData = Util.getDeviceData();
    JSONObject devicePayload = new JSONObject(deviceData);
    NameValuePair devicePayloadPair = new BasicNameValuePair("device_data", devicePayload.toString());
    pairs.add(devicePayloadPair);

    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs);
    entity.setContentType(URLEncodedUtils.CONTENT_TYPE);
    request.setEntity(entity);

    return request;
}

From source file:com.addthis.hydra.query.web.GoogleDriveAuthentication.java

/**
 * Use the Google authorization token to obtain a Google access token.
 * Google OAuth2 your documentation is sorely lacking.
 *
 * @param kv store the access token as a (key, value) pair
 * @return true if the access token was retrieved
 *///from w w  w  .j  ava2  s . c  o m
static boolean gdriveAccessToken(KVPairs kv, ChannelHandlerContext ctx) throws Exception {
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse httpResponse = null;
    if (kv.hasKey(autherror)) {
        sendErrorMessage(ctx,
                "Error while attempting to authorize google drive access: " + kv.getValue(autherror));
        return false;
    } else if (!kv.hasKey(authtoken)) {
        sendErrorMessage(ctx, "Error while attempting to authorize google drive access: "
                + "authorization token is missing.");
        return false;
    }
    try {
        String code = kv.getValue(authtoken);
        httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("https://accounts.google.com/o/oauth2/token");
        httpPost.setHeader(HttpHeaders.Names.CONTENT_TYPE, URLEncodedUtils.CONTENT_TYPE);
        Set<NameValuePair> parameters = new HashSet<>();
        // Why is this redirect_uri required??? It appeared to be unused by the protocol.
        parameters.add(new BasicNameValuePair("redirect_uri",
                "http://" + generateTargetHostName() + ":2222/query/google/submit"));
        parameters.add(new BasicNameValuePair("code", code));
        parameters.add(new BasicNameValuePair("client_id", gdriveClientId));
        parameters.add(new BasicNameValuePair("client_secret", gdriveClientSecret));
        parameters.add(new BasicNameValuePair("grant_type", "authorization_code"));
        httpPost.setEntity(new StringEntity(URLEncodedUtils.format(parameters, Charset.defaultCharset()),
                StandardCharsets.UTF_8));
        httpResponse = httpClient.execute(httpPost);
        if (httpResponse.getStatusLine().getStatusCode() != HttpResponseStatus.OK.code()) {
            sendErrorMessage(ctx, "Error while attempting to exchange the authorization token "
                    + "for the access token: " + httpResponse.getStatusLine().getReasonPhrase());
            return false;
        }
        String responseEntity = EntityUtils.toString(httpResponse.getEntity());
        JSONObject response = new JSONObject(responseEntity);
        if (response.has("error")) {
            sendErrorMessage(ctx, "Error while attempting to exchange the authorization token "
                    + "for the access token: " + response.getString("error_description"));
            return false;
        } else if (!response.has("access_token")) {
            sendErrorMessage(ctx, "Error while attempting to exchange the authorization token "
                    + "for the access token: No access token received.");
            return false;
        }
        kv.addValue("accesstoken", response.getString("access_token"));
        return true;
    } finally {
        closeResource(httpResponse);
        closeResource(httpClient);
    }
}

From source file:com.adjust.sdk.RequestHandler.java

private HttpUriRequest getRequest(ActivityPackage activityPackage) throws UnsupportedEncodingException {
    String url = Constants.BASE_URL + activityPackage.getPath();
    HttpPost request = new HttpPost(url);

    String language = Locale.getDefault().getLanguage();
    request.addHeader("User-Agent", activityPackage.getUserAgent());
    request.addHeader("Client-SDK", activityPackage.getClientSdk());
    request.addHeader("Accept-Language", language);

    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    for (Map.Entry<String, String> entity : activityPackage.getParameters().entrySet()) {
        NameValuePair pair = new BasicNameValuePair(entity.getKey(), entity.getValue());
        pairs.add(pair);//from   w w w  .  j  ava  2  s  .co m
    }

    long now = System.currentTimeMillis();
    String dateString = Util.dateFormat(now);
    NameValuePair sentAtPair = new BasicNameValuePair("sent_at", dateString);
    pairs.add(sentAtPair);

    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs);
    entity.setContentType(URLEncodedUtils.CONTENT_TYPE);
    request.setEntity(entity);

    return request;
}

From source file:org.herrlado.websms.connector.magtifunge.ConnectorMagtifun.java

/**
 * Create and Prepare a Post Request. Set also an User-Agent
 * //  w w  w .ja  v  a2s  . c o  m
 * @param url
 *            http post url
 * @param urlencodedparams
 *            key=value pairs as url encoded string
 * @return HttpPost
 * @throws Exception
 *             if an error occures
 */
private static HttpPost createPOST(final String url, final String urlencodedparams) throws Exception {
    final HttpPost post = new HttpPost(url);
    post.setHeader("User-Agent", FAKE_USER_AGENT);
    post.setHeader(new BasicHeader(HTTP.CONTENT_TYPE, URLEncodedUtils.CONTENT_TYPE));
    post.setEntity(new StringEntity(urlencodedparams));
    return post;
}

From source file:org.herrlado.websms.connector.smsge.ConnectorSmsge.java

/**
 * Create and Prepare a Post Request. Set also an User-Agent
 * //from ww  w.j  a  v  a2s .  c  o  m
 * @param url
 *            http post url
 * @param urlencodedparams
 *            key=value pairs as url encoded string
 * @return HttpPost
 * @throws Exception
 *             if an error occures
 */
private static HttpPost createPOST(final String url) throws Exception {
    final HttpPost post = new HttpPost(url);
    post.setHeader("User-Agent", FAKE_USER_AGENT);
    post.setHeader(new BasicHeader(HTTP.CONTENT_TYPE, URLEncodedUtils.CONTENT_TYPE));
    return post;
}

From source file:com.gargoylesoftware.htmlunit.HttpWebConnection.java

/**
 * Creates an <tt>HttpMethod</tt> instance according to the specified parameters.
 * @param webRequest the request/*from   w ww.j  a  v a  2  s  .  co  m*/
 * @param httpClientBuilder the httpClientBuilder that will be configured
 * @return the <tt>HttpMethod</tt> instance constructed according to the specified parameters
 * @throws IOException
 * @throws URISyntaxException
 */
@SuppressWarnings("deprecation")
private HttpUriRequest makeHttpMethod(final WebRequest webRequest, final HttpClientBuilder httpClientBuilder)
        throws IOException, URISyntaxException {

    final String charset = webRequest.getCharset();

    // Make sure that the URL is fully encoded. IE actually sends some Unicode chars in request
    // URLs; because of this we allow some Unicode chars in URLs. However, at this point we're
    // handing things over the HttpClient, and HttpClient will blow up if we leave these Unicode
    // chars in the URL.
    final URL url = UrlUtils.encodeUrl(webRequest.getUrl(), false, charset);

    // URIUtils.createURI is deprecated but as of httpclient-4.2.1, URIBuilder doesn't work here as it encodes path
    // what shouldn't happen here
    URI uri = URIUtils.createURI(url.getProtocol(), url.getHost(), url.getPort(), url.getPath(),
            escapeQuery(url.getQuery()), null);
    if (getVirtualHost() != null) {
        uri = URI.create(getVirtualHost());
    }
    final HttpRequestBase httpMethod = buildHttpMethod(webRequest.getHttpMethod(), uri);
    setProxy(httpMethod, webRequest);
    if (!(httpMethod instanceof HttpEntityEnclosingRequest)) {
        // this is the case for GET as well as TRACE, DELETE, OPTIONS and HEAD
        if (!webRequest.getRequestParameters().isEmpty()) {
            final List<NameValuePair> pairs = webRequest.getRequestParameters();
            final org.apache.http.NameValuePair[] httpClientPairs = NameValuePair.toHttpClient(pairs);
            final String query = URLEncodedUtils.format(Arrays.asList(httpClientPairs), charset);
            uri = URIUtils.createURI(url.getProtocol(), url.getHost(), url.getPort(), url.getPath(), query,
                    null);
            httpMethod.setURI(uri);
        }
    } else { // POST as well as PUT and PATCH
        final HttpEntityEnclosingRequest method = (HttpEntityEnclosingRequest) httpMethod;

        if (webRequest.getEncodingType() == FormEncodingType.URL_ENCODED && method instanceof HttpPost) {
            final HttpPost postMethod = (HttpPost) method;
            if (webRequest.getRequestBody() == null) {
                final List<NameValuePair> pairs = webRequest.getRequestParameters();
                final org.apache.http.NameValuePair[] httpClientPairs = NameValuePair.toHttpClient(pairs);
                final String query = URLEncodedUtils.format(Arrays.asList(httpClientPairs), charset);
                final StringEntity urlEncodedEntity = new StringEntity(query, charset);
                urlEncodedEntity.setContentType(URLEncodedUtils.CONTENT_TYPE);
                postMethod.setEntity(urlEncodedEntity);
            } else {
                final String body = StringUtils.defaultString(webRequest.getRequestBody());
                final StringEntity urlEncodedEntity = new StringEntity(body, charset);
                urlEncodedEntity.setContentType(URLEncodedUtils.CONTENT_TYPE);
                postMethod.setEntity(urlEncodedEntity);
            }
        } else if (FormEncodingType.MULTIPART == webRequest.getEncodingType()) {
            final Charset c = getCharset(charset, webRequest.getRequestParameters());
            final MultipartEntityBuilder builder = MultipartEntityBuilder.create().setLaxMode();
            builder.setCharset(c);

            for (final NameValuePair pair : webRequest.getRequestParameters()) {
                if (pair instanceof KeyDataPair) {
                    buildFilePart((KeyDataPair) pair, builder);
                } else {
                    builder.addTextBody(pair.getName(), pair.getValue(),
                            ContentType.create("text/plain", charset));
                }
            }
            method.setEntity(builder.build());
        } else { // for instance a PUT or PATCH request
            final String body = webRequest.getRequestBody();
            if (body != null) {
                method.setEntity(new StringEntity(body, charset));
            }
        }
    }

    configureHttpProcessorBuilder(httpClientBuilder, webRequest);

    // Tell the client where to get its credentials from
    // (it may have changed on the webClient since last call to getHttpClientFor(...))
    final CredentialsProvider credentialsProvider = webClient_.getCredentialsProvider();

    // if the used url contains credentials, we have to add this
    final Credentials requestUrlCredentials = webRequest.getUrlCredentials();
    if (null != requestUrlCredentials && webClient_.getBrowserVersion().hasFeature(URL_AUTH_CREDENTIALS)) {
        final URL requestUrl = webRequest.getUrl();
        final AuthScope authScope = new AuthScope(requestUrl.getHost(), requestUrl.getPort());
        // updating our client to keep the credentials for the next request
        credentialsProvider.setCredentials(authScope, requestUrlCredentials);
        httpContext_.removeAttribute(HttpClientContext.TARGET_AUTH_STATE);
    }

    // if someone has set credentials to this request, we have to add this
    final Credentials requestCredentials = webRequest.getCredentials();
    if (null != requestCredentials) {
        final URL requestUrl = webRequest.getUrl();
        final AuthScope authScope = new AuthScope(requestUrl.getHost(), requestUrl.getPort());
        // updating our client to keep the credentials for the next request
        credentialsProvider.setCredentials(authScope, requestCredentials);
        httpContext_.removeAttribute(HttpClientContext.TARGET_AUTH_STATE);
    }
    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    httpContext_.removeAttribute(HttpClientContext.CREDS_PROVIDER);

    return httpMethod;
}

From source file:edu.mit.mobile.android.locast.net.NetworkClient.java

/**
 * Makes a request to pair the device with the server. The server sends back a set of
 * credentials which are then stored for making further queries.
 *
 * @param pairCode/*  ww  w . j  a  va  2s  .  c om*/
 *            the unique code that is provided by the server.
 * @return true if pairing process was successful, otherwise false.
 * @throws IOException
 * @throws JSONException
 * @throws RecordStoreException
 * @throws NetworkProtocolException
 */
public boolean pairDevice(String pairCode) throws IOException, JSONException, NetworkProtocolException {
    final DefaultHttpClient hc = new DefaultHttpClient();
    hc.addRequestInterceptor(REMOVE_EXPECTATIONS);
    final HttpPost r = new HttpPost(getFullUrlAsString(PATH_PAIR));

    final List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
    parameters.add(new BasicNameValuePair("auth_secret", pairCode));
    r.setEntity(new UrlEncodedFormEntity(parameters));

    r.setHeader("Content-Type", URLEncodedUtils.CONTENT_TYPE);
    final HttpResponse c = hc.execute(r);

    checkStatusCode(c, false);

    // final JSONObject creds = toJsonObject(c);

    return true;
}

From source file:net.java.sip.communicator.service.httputil.HttpUtils.java

/**
 * Posting form to <tt>address</tt>. For submission we use POST method
 * which is "application/x-www-form-urlencoded" encoded.
 * @param httpClient the http client//from  w  w w.j a  v a 2  s.  co m
 * @param postMethod the post method
 * @param address HTTP address.
 * @param formParamNames the parameter names to include in post.
 * @param formParamValues the corresponding parameter values to use.
 * @param usernameParamIx the index of the username parameter in the
 * <tt>formParamNames</tt> and <tt>formParamValues</tt>
 * if any, otherwise -1.
 * @param passwordParamIx the index of the password parameter in the
 * <tt>formParamNames</tt> and <tt>formParamValues</tt>
 * if any, otherwise -1.
 * @param headerParamNames additional header name to include
 * @param headerParamValues corresponding header value to include
 * @return the result or null if send was not possible or
 * credentials ask if any was canceled.
 */
private static HttpEntity postForm(DefaultHttpClient httpClient, HttpPost postMethod, String address,
        ArrayList<String> formParamNames, ArrayList<String> formParamValues, int usernameParamIx,
        int passwordParamIx, RedirectHandler redirectHandler, List<String> headerParamNames,
        List<String> headerParamValues) throws Throwable {
    // if we have username and password in the parameters, lets
    // retrieve their values
    // if there are already filled skip asking the user
    Credentials creds = null;
    if (usernameParamIx != -1 && usernameParamIx < formParamNames.size() && passwordParamIx != -1
            && passwordParamIx < formParamNames.size()
            && (formParamValues.get(usernameParamIx) == null
                    || formParamValues.get(usernameParamIx).length() == 0)
            && (formParamValues.get(passwordParamIx) == null
                    || formParamValues.get(passwordParamIx).length() == 0)) {
        URL url = new URL(address);
        HTTPCredentialsProvider prov = (HTTPCredentialsProvider) httpClient.getCredentialsProvider();

        // don't allow empty username
        while (creds == null || creds.getUserPrincipal() == null
                || StringUtils.isNullOrEmpty(creds.getUserPrincipal().getName())) {
            creds = prov.getCredentials(new AuthScope(url.getHost(), url.getPort()));

            // it was user canceled lets stop processing
            if (creds == null && !prov.retry()) {
                return null;
            }
        }
    }

    // construct the name value pairs we will be sending
    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    // there can be no params
    if (formParamNames != null) {
        for (int i = 0; i < formParamNames.size(); i++) {
            // we are on the username index, insert retrieved username value
            if (i == usernameParamIx && creds != null) {
                parameters
                        .add(new BasicNameValuePair(formParamNames.get(i), creds.getUserPrincipal().getName()));
            } // we are on the password index, insert retrieved password val
            else if (i == passwordParamIx && creds != null) {
                parameters.add(new BasicNameValuePair(formParamNames.get(i), creds.getPassword()));
            } else // common name value pair, all info is present
            {
                parameters.add(new BasicNameValuePair(formParamNames.get(i), formParamValues.get(i)));
            }
        }
    }

    // our custom strategy, will check redirect handler should we redirect
    // if missing will use the default handler
    httpClient.setRedirectStrategy(new CustomRedirectStrategy(redirectHandler, parameters));

    // Uses String UTF-8 to keep compatible with android version and
    // older versions of the http client libs, as the one used
    // in debian (4.1.x)
    String s = URLEncodedUtils.format(parameters, "UTF-8");
    StringEntity entity = new StringEntity(s, "UTF-8");
    // set content type to "application/x-www-form-urlencoded"
    entity.setContentType(URLEncodedUtils.CONTENT_TYPE);

    // insert post values encoded.
    postMethod.setEntity(entity);

    if (headerParamNames != null) {
        for (int i = 0; i < headerParamNames.size(); i++) {
            postMethod.addHeader(headerParamNames.get(i), headerParamValues.get(i));
        }
    }

    // execute post
    return executeMethod(httpClient, postMethod, redirectHandler, parameters);
}

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;//from  w ww  .  j  a  v  a  2 s . 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;

}