List of usage examples for org.apache.http.params HttpProtocolParams setContentCharset
public static void setContentCharset(HttpParams httpParams, String str)
From source file:com.yozio.android.Yozio.java
static HttpClient threadSafeHttpClient() { HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry); return new DefaultHttpClient(cm, params); }
From source file:com.lgallardo.youtorrentcontroller.JSONParser.java
public void postCommand(String command, String hash) throws JSONParserStatusCodeException { String key = "hash"; String urlContentType = "application/x-www-form-urlencoded"; String boundary = null;//from w w w .j av a 2 s.co m StringBuilder fileContent = null; HttpResponse httpResponse; DefaultHttpClient httpclient; String url = ""; // Log.d("Debug", "JSONParser - command: " + command); if ("start".equals(command) || "startSelected".equals(command)) { url = url + "gui/?action=start&hash=" + hash; } if ("pause".equals(command) || "pauseSelected".equals(command)) { url = url + "gui/?action=pause&hash=" + hash; } if ("stop".equals(command) || "stopSelected".equals(command)) { url = url + "gui/?action=stop&hash=" + hash; Log.d("Debug", "Stoping torrent " + hash); } if ("delete".equals(command) || "deleteSelected".equals(command)) { url = url + "gui/?action=remove&hash=" + hash.replace("|", "&hash="); key = "hashes"; } if ("deleteDrive".equals(command) || "deleteDriveSelected".equals(command)) { url = url + "gui/?action=removedata&hash=" + hash.replace("|", "&hash="); key = "hashes"; } if ("addTorrent".equals(command)) { URI hash_uri = null; try { hash_uri = new URI(hash); hash = hash_uri.toString(); // Log.d("Debug","Torrent URL: "+ hash); } catch (URISyntaxException e) { Log.e("Debug", "URISyntaxException: " + e.toString()); } url = url + "gui/?action=add-url&s=" + hash; // key = "urls"; } if ("addTorrentFile".equals(command)) { url = url + "gui/?action=add-file"; key = "urls"; boundary = "-----------------------" + (new Date()).getTime(); urlContentType = "multipart/form-data; boundary=" + boundary; // urlContentType = "multipart/form-data"; } // 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 = url + "gui/?action=queueup&hash=" + hash.replace("|", "&hash="); key = "hashes"; } if ("decreasePrio".equals(command)) { url = url + "gui/?action=queuedown&hash=" + hash.replace("|", "&hash="); key = "hashes"; } if ("maxPrio".equals(command)) { url = url + "gui/?action=queuetop&hash=" + hash.replace("|", "&hash="); key = "hashes"; } if ("minPrio".equals(command)) { url = url + "gui/?action=queuebottom&hash=" + hash.replace("|", "&hash="); key = "hashes"; } if ("setQBittorrentPrefefrences".equals(command)) { url = "command/setPreferences"; key = "json"; } if ("recheckSelected".equals(command)) { url = url + "gui/?action=recheck&hash=" + hash.replace("|", "&hash="); } // if ("toggleFirstLastPiecePrio".equals(command)) { // url = "command/toggleFirstLastPiecePrio"; // key = "hashes"; // // } // // if ("toggleSequentialDownload".equals(command)) { // url = "command/toggleSequentialDownload"; // 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, "youTorrent Controller"); 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(); // Set http parameters 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 + "&token=" + token; // Log.d("Debug", "JSONParser - url: " + url); HttpPost httpget = new HttpPost(url); if ("addTorrent".equals(command)) { URI hash_uri = new URI(hash); hash = hash_uri.toString(); } // In order to pass the has we must set the pair name value BasicNameValuePair bnvp = new BasicNameValuePair(key, hash); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(bnvp); httpget.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); // Set content type and urls if ("increasePrio".equals(command) || "decreasePrio".equals(command) || "maxPrio".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)) { // Log.d("Debug", "JSONParser - urlContentType: " + urlContentType); // Log.d("Debug", "JSONParser - hash: " + Uri.decode(URLEncoder.encode(hash, "UTF-8"))); // Log.d("Debug", "JSONParser - hash: " + hash); 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("torrent_file", file, ContentType.DEFAULT_BINARY, null); // builder.addBinaryBody("upfile", file, ContentType.create(urlContentType), 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(); if (mStatusCode != 200) { httpclient.getConnectionManager().shutdown(); throw new JSONParserStatusCodeException(mStatusCode); } HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { } catch (ClientProtocolException e) { Log.e("Debug", "Client: " + e.toString()); e.printStackTrace(); } catch (IOException e) { Log.e("Debug", "IO: " + e.toString()); // e.printStackTrace(); 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(); } }
From source file:org.dasein.cloud.tier3.APIHandler.java
private @Nonnull HttpClient getClient(URI uri) throws InternalException, CloudException { ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new NoContextException(); }// w w w. java 2s . c o m boolean ssl = uri.getScheme().startsWith("https"); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); // noinspection deprecation HttpProtocolParams.setContentCharset(params, Consts.UTF_8.toString()); HttpProtocolParams.setUserAgent(params, "Dasein Cloud"); params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000); params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 300000); Properties p = ctx.getCustomProperties(); if (p != null) { String proxyHost = p.getProperty("proxyHost"); String proxyPort = p.getProperty("proxyPort"); if (proxyHost != null) { int port = 0; if (proxyPort != null && proxyPort.length() > 0) { port = Integer.parseInt(proxyPort); } params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, port, ssl ? "https" : "http")); } } return new DefaultHttpClient(); }
From source file:com.curso.listadapter.net.RESTClient.java
/** * * this private method obtains the httpclient that support https * and set the timeout in 30 secconds//w ww .j a va 2 s.com * * * */ public HttpClient getNewHttpClient() { try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); MySSLSocketFactory sf = new MySSLSocketFactory(trustStore); sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpConnectionParams.setConnectionTimeout(params, RequestTimeOut); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); return new DefaultHttpClient(ccm, params); } catch (Exception e) { return new DefaultHttpClient(); } }
From source file:com.pc.dailymile.DailyMileClient.java
private void initHttpClient() { HttpParams parameters = new BasicHttpParams(); HttpProtocolParams.setVersion(parameters, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(parameters, HTTP.DEFAULT_CONTENT_CHARSET); // set the User-Agent to a common User-Agent because currently // the default httpclient User-Agent doesn't work with dailymile HttpProtocolParams.setUserAgent(parameters, "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"); HttpProtocolParams.setUseExpectContinue(parameters, false); HttpConnectionParams.setTcpNoDelay(parameters, true); SchemeRegistry schReg = new SchemeRegistry(); schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); ClientConnectionManager tsccm = new ThreadSafeClientConnManager(parameters, schReg); DefaultHttpClient defaultHttpClient = new DefaultHttpClient(tsccm, parameters); defaultHttpClient.addRequestInterceptor(new HttpRequestInterceptor() { public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (!request.containsHeader("Accept-Encoding")) { request.addHeader("Accept-Encoding", "gzip"); }/*from w w w .j a v a 2 s . c om*/ } }); defaultHttpClient.addResponseInterceptor(new HttpResponseInterceptor() { public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); Header ceheader = entity.getContentEncoding(); if (ceheader != null) { HeaderElement[] codecs = ceheader.getElements(); for (int i = 0; i < codecs.length; i++) { if (codecs[i].getName().equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } }); httpClient = defaultHttpClient; }
From source file:com.klinker.android.twitter.utils.api_helper.TwitterMultipleImageHelper.java
public String getMediaIds(File[] pics, Twitter twitter) { JSONObject jsonresponse = new JSONObject(); String ids = ""; for (int i = 0; i < pics.length; i++) { File file = pics[i];//from ww w. j a va 2 s . c o m try { AccessToken token = twitter.getOAuthAccessToken(); String oauth_token = token.getToken(); String oauth_token_secret = token.getTokenSecret(); // generate authorization header String get_or_post = "POST"; String oauth_signature_method = "HMAC-SHA1"; String uuid_string = UUID.randomUUID().toString(); uuid_string = uuid_string.replaceAll("-", ""); String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here // get the timestamp Calendar tempcal = Calendar.getInstance(); long ts = tempcal.getTimeInMillis();// get current time in milliseconds String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds // the parameter string must be in alphabetical order, "text" parameter added at end String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0"; System.out.println("Twitter.updateStatusWithMedia(): parameter_string=" + parameter_string); String twitter_endpoint = "https://upload.twitter.com/1.1/media/upload.json"; String twitter_endpoint_host = "upload.twitter.com"; String twitter_endpoint_path = "/1.1/media/upload.json"; String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&" + encode(parameter_string); String oauth_signature = computeSignature(signature_base_string, AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret)); String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\""; HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "HttpCore/1.1"); HttpProtocolParams.setUseExpectContinue(params, false); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); HttpHost host = new HttpHost(twitter_endpoint_host, 443); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); try { try { SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, null, null); SSLSocketFactory ssf = sslcontext.getSocketFactory(); Socket socket = ssf.createSocket(); socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0); conn.bind(socket, params); BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("POST", twitter_endpoint_path); // need to add status parameter to this POST MultipartEntity reqEntity = new MultipartEntity(); FileBody sb_image = new FileBody(file); reqEntity.addPart("media", sb_image); request2.setEntity(reqEntity); request2.setParams(params); request2.addHeader("Authorization", authorization_header_string); System.out.println( "Twitter.updateStatusWithMedia(): Entity, params and header added to request. Preprocessing and executing..."); httpexecutor.preProcess(request2, httpproc, context); HttpResponse response2 = httpexecutor.execute(request2, conn, context); System.out.println("Twitter.updateStatusWithMedia(): ... done. Postprocessing..."); response2.setParams(params); httpexecutor.postProcess(response2, httpproc, context); String responseBody = EntityUtils.toString(response2.getEntity()); System.out.println("Twitter.updateStatusWithMedia(): done. response=" + responseBody); // error checking here. Otherwise, status should be updated. jsonresponse = new JSONObject(responseBody); if (jsonresponse.has("errors")) { JSONObject temp_jo = new JSONObject(); temp_jo.put("response_status", "error"); temp_jo.put("message", jsonresponse.getJSONArray("errors").getJSONObject(0).getString("message")); temp_jo.put("twitter_code", jsonresponse.getJSONArray("errors").getJSONObject(0).getInt("code")); jsonresponse = temp_jo; } // add it to the media_ids string ids += jsonresponse.getString("media_id_string"); if (i != pics.length - 1) { ids += ","; } conn.close(); } catch (HttpException he) { System.out.println(he.getMessage()); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatusWithMedia HttpException message=" + he.getMessage()); return null; } catch (NoSuchAlgorithmException nsae) { System.out.println(nsae.getMessage()); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatusWithMedia NoSuchAlgorithmException message=" + nsae.getMessage()); return null; } catch (KeyManagementException kme) { System.out.println(kme.getMessage()); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatusWithMedia KeyManagementException message=" + kme.getMessage()); return null; } finally { conn.close(); } } catch (IOException ioe) { ioe.printStackTrace(); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatusWithMedia IOException message=" + ioe.getMessage()); return null; } } catch (Exception e) { return null; } } return ids; }
From source file:org.dasein.cloud.skeleton.RESTMethod.java
private @Nonnull HttpClient getClient(URI uri) throws InternalException, CloudException { ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new NoContextException(); }/* w w w . j a v a 2s .c o m*/ boolean ssl = uri.getScheme().startsWith("https"); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); //noinspection deprecation HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpProtocolParams.setUserAgent(params, "Dasein Cloud"); params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000); params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 300000); Properties p = ctx.getCustomProperties(); if (p != null) { String proxyHost = p.getProperty("proxyHost"); String proxyPort = p.getProperty("proxyPort"); if (proxyHost != null) { int port = 0; if (proxyPort != null && proxyPort.length() > 0) { port = Integer.parseInt(proxyPort); } params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, port, ssl ? "https" : "http")); } } return new DefaultHttpClient(params); }
From source file:com.imaginary.home.cloud.CloudTest.java
static private @Nonnull HttpClient getClient() { HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); //noinspection deprecation HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpProtocolParams.setUserAgent(params, "Imaginary Home"); return new DefaultHttpClient(params); }
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;/* www . j a v a 2s. co 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; }