List of usage examples for org.apache.http.impl.client DefaultHttpClient setParams
public synchronized void setParams(final HttpParams params)
From source file:com.lgallardo.youtorrentcontroller.JSONParser.java
public JSONArray getJSONArrayFromUrl(String url) throws JSONParserStatusCodeException { // if server is published in a subfolder, fix url if (subfolder != null && !subfolder.equals("")) { url = subfolder + "/" + url; }//from w w w .j a va 2 s.co m HttpResponse httpResponse; DefaultHttpClient httpclient; 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"); HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8); // Making HTTP request HttpHost targetHost = new HttpHost(hostname, port, protocol); httpclient = getNewHttpClient(); // Set http parameters httpclient.setParams(httpParameters); try { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); httpclient.getCredentialsProvider().setCredentials(authScope, credentials); url = protocol + "://" + hostname + ":" + port + "/" + url; HttpGet httpget = new HttpGet(url); if (this.cookie != null) { httpget.setHeader("Cookie", this.cookie); } 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(); // Build JSON BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); jArray = new JSONArray(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } catch (UnsupportedEncodingException e) { } catch (ClientProtocolException e) { Log.e("JSON", "Client: " + e.toString()); e.printStackTrace(); } catch (IOException e) { Log.e("JSON", "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("JSON", "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 JSON String return jArray; }
From source file:com.lgallardo.youtorrentcontroller.JSONParser.java
public String getApi() throws JSONParserStatusCodeException { String url = "version/api"; // if server is publish in a subfolder, fix url if (subfolder != null && !subfolder.equals("")) { url = subfolder + "/" + url; }/*w ww . j ava 2 s. c o m*/ String APIVersionString = null; HttpResponse httpResponse; DefaultHttpClient httpclient; 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(hostname, port, 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); // set http parameters url = protocol + "://" + hostname + ":" + port + "/" + url; HttpGet httpget = new HttpGet(url); HttpResponse response = httpclient.execute(targetHost, httpget); HttpEntity entity = response.getEntity(); StatusLine statusLine = response.getStatusLine(); int mStatusCode = statusLine.getStatusCode(); // Log.d("Debug", "API - mStatusCode: " + mStatusCode); if (mStatusCode == 200) { // Save API APIVersionString = EntityUtils.toString(response.getEntity()); // Log.d("Debug", "API - ApiString: " + APIVersionString); } if (entity != null) { entity.consumeContent(); } // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } catch (Exception e) { // Log.i("APIVer", "Exception " + e.toString()); } // if (APIVersionString == null) { // APIVersionString = ""; // } return APIVersionString; }
From source file:org.tellervo.desktop.wsi.WSIServerDetails.java
/** * Ping the server to update status/*from w w w. ja v a 2 s . co m*/ * * @return */ public boolean pingServer() { // First make sure we have a network connection try { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface nic = interfaces.nextElement(); if (nic.isLoopback()) continue; if (nic.isUp()) { log.debug("Network adapter '" + nic.getDisplayName() + "' is up"); isNetworkConnected = true; } } } catch (Exception e) { e.printStackTrace(); } if (!isNetworkConnected) { status = WSIServerStatus.NO_CONNECTION; errMessage = "You do not appear to have a network connection.\nPlease check you network and try again."; return false; } URI url = null; BufferedReader dis = null; DefaultHttpClient client = new DefaultHttpClient(); try { String path = App.prefs.getPref(PrefKey.WEBSERVICE_URL, "invalid-url!"); url = new URI(path.trim()); // Check we're accessing HTTP or HTTPS connection if (url.getScheme() == null || ((!url.getScheme().equals("http")) && !url.getScheme().equals("https"))) { errMessage = "The webservice URL is invalid. It should begin http or https"; log.debug(errMessage); status = WSIServerStatus.STATUS_ERROR; return false; } // load cookies client.setCookieStore(WSCookieStoreHandler.getCookieStore().toCookieStore()); if (App.prefs.getBooleanPref(PrefKey.WEBSERVICE_USE_STRICT_SECURITY, false)) { // Using strict security so don't allow self signed certificates for SSL } else { // Not using strict security so allow self signed certificates for SSL if (url.getScheme().equals("https")) WebJaxbAccessor.setSelfSignableHTTPSScheme(client); } HttpGet req = new HttpGet(url); HttpParams httpParameters = new BasicHttpParams(); int timeoutConnection = 3000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = 5000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); client.setParams(httpParameters); HttpResponse response = client.execute(req); if (response.getStatusLine().getStatusCode() == 200) { InputStream responseIS = response.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(responseIS)); String s = ""; while ((s = reader.readLine()) != null) { if (s.contains("<webserviceVersion>")) { String[] strparts = s.split("<[/]*webserviceVersion>"); if (strparts.length > 0) parserThisServerVersion(strparts[1]); status = WSIServerStatus.VALID; return true; } else if (s.startsWith("<b>Parse error</b>:")) { status = WSIServerStatus.STATUS_ERROR; errMessage = s.replace("<b>", "").replace("</b>", "").replace("<br />", ""); return false; } } } else if (response.getStatusLine().getStatusCode() == 403) { String serverType = ""; try { serverType = "(" + response.getHeaders("Server")[0].getValue() + ")"; } catch (Exception e) { } errMessage = "The webserver " + serverType + " reports you do not have permission to access this URL.\n" + "This is a problem with the server setup, not your Tellervo username/password.\n" + "Contact your systems administrator for help."; log.debug(errMessage); status = WSIServerStatus.STATUS_ERROR; return false; } else if (response.getStatusLine().getStatusCode() == 404) { errMessage = "Server reports that there is no webservice at this URL.\nPlease check and try again."; log.debug(errMessage); status = WSIServerStatus.URL_NOT_TELLERVO_WS; return false; } else if (response.getStatusLine().getStatusCode() == 407) { errMessage = "Proxy authentication is required to access this server.\nCheck your proxy server settings and try again."; log.debug(errMessage); status = WSIServerStatus.STATUS_ERROR; return false; } else if (response.getStatusLine().getStatusCode() >= 500) { errMessage = "Internal server error (code " + response.getStatusLine().getStatusCode() + ").\nContact your systems administrator"; log.debug(errMessage); status = WSIServerStatus.STATUS_ERROR; return false; } else if (response.getStatusLine().getStatusCode() >= 300 && response.getStatusLine().getStatusCode() < 400) { errMessage = "Server reports that your request has been redirected to a different URL.\nCheck your URL and try again."; log.debug(errMessage); status = WSIServerStatus.STATUS_ERROR; return false; } else { errMessage = "The server is returning an error:\nCode: " + response.getStatusLine().getStatusCode() + "\n" + response.getStatusLine().getReasonPhrase(); log.debug(errMessage); status = WSIServerStatus.STATUS_ERROR; return false; } } catch (ClientProtocolException e) { errMessage = "There was as problem with the HTTP protocol.\nPlease contact the Tellervo developers."; log.debug(errMessage); status = WSIServerStatus.STATUS_ERROR; return false; } catch (SSLPeerUnverifiedException sslex) { errMessage = "You have strict security policy enabled but the server you are connecting to does not have a valid SSL certificate."; log.debug(errMessage); status = WSIServerStatus.SSL_CERTIFICATE_PROBLEM; return false; } catch (IOException e) { if (url.toString().startsWith("http://10.")) { // Provide extra help to those failing to access a local server address errMessage = "There is no response from the server at this URL. Are you sure this is the correct address?\n\nPlease note that the URL you have specified is a local network address. You will need to be on the same network as the server to gain access."; } else if (e.getMessage().contains("hostname in certificate didn't match")) { errMessage = "The security certificate for this server is for a different domain. This could be an indication of a 'man-in-the-middle' attack."; } else { errMessage = "There is no response from the server at this URL.\nAre you sure this is the correct address and that\nthe server is turned on and configured correctly?"; } log.debug(errMessage); log.debug("IOException " + e.getLocalizedMessage()); status = WSIServerStatus.URL_NOT_RESPONDING; return false; } catch (URISyntaxException e) { errMessage = "The web service URL you entered was malformed.\nPlease check for typos and try again."; log.debug(errMessage); status = WSIServerStatus.MALFORMED_URL; return false; } catch (IllegalStateException e) { errMessage = "This communications protocol is not supported.\nPlease contact your systems administrator."; log.debug(errMessage); status = WSIServerStatus.MALFORMED_URL; return false; } catch (Exception e) { errMessage = "The URL you specified exists, but does not appear to be a Tellervo webservice.\nPlease check and try again."; log.debug(errMessage); status = WSIServerStatus.URL_NOT_TELLERVO_WS; return false; } finally { try { if (dis != null) { dis.close(); } } catch (IOException e) { } } status = WSIServerStatus.URL_NOT_TELLERVO_WS; return false; }
From source file:com.lgallardo.youtorrentcontroller.JSONParser.java
public String getNewCookie() throws JSONParserStatusCodeException { String url = "login"; // if server is publish in a subfolder, fix url if (subfolder != null && !subfolder.equals("")) { url = subfolder + "/" + url; }// w w w . j a v a2s .c o m String cookieString = null; HttpResponse httpResponse; DefaultHttpClient httpclient; 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(hostname, port, 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; HttpPost httpget = new HttpPost(url); // // In order to pass the username and password we must set the pair name value List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("username", this.username)); nvps.add(new BasicNameValuePair("password", this.password)); httpget.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); HttpResponse response = httpclient.execute(targetHost, httpget); HttpEntity entity = response.getEntity(); StatusLine statusLine = response.getStatusLine(); int mStatusCode = statusLine.getStatusCode(); if (mStatusCode == 200) { // Save cookie List<Cookie> cookies = httpclient.getCookieStore().getCookies(); if (!cookies.isEmpty()) { cookieString = cookies.get(0).getName() + "=" + cookies.get(0).getValue() + "; domain=" + cookies.get(0).getDomain(); cookieString = cookies.get(0).getName() + "=" + cookies.get(0).getValue(); } } if (entity != null) { entity.consumeContent(); } // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } catch (Exception e) { Log.e("Debug", "Exception " + e.toString()); } if (cookieString == null) { cookieString = ""; } return cookieString; }
From source file:com.lgallardo.youtorrentcontroller.JSONParser.java
public String[] getToken() throws JSONParserStatusCodeException { String url = "gui/token.html"; // if server is publish in a subfolder, fix url if (subfolder != null && !subfolder.equals("")) { url = subfolder + "/" + url; }//from w w w . j a v a2s . c o m String tokenString = null; String cookieString = "NULL"; HttpResponse httpResponse; DefaultHttpClient httpclient; 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(hostname, port, 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; HttpGet httpget = new HttpGet(url); HttpResponse response = httpclient.execute(targetHost, httpget); HttpEntity entity = response.getEntity(); StatusLine statusLine = response.getStatusLine(); int mStatusCode = statusLine.getStatusCode(); // Log.d("Debug", "Token - mStatusCode: " + mStatusCode); if (mStatusCode != 200) { httpclient.getConnectionManager().shutdown(); throw new JSONParserStatusCodeException(mStatusCode); } if (mStatusCode == 200) { // Save cookie List<Cookie> cookies = httpclient.getCookieStore().getCookies(); if (!cookies.isEmpty()) { cookieString = cookies.get(0).getName() + "=" + cookies.get(0).getValue() + "; domain=" + cookies.get(0).getDomain(); cookieString = cookies.get(0).getName() + "=" + cookies.get(0).getValue(); } // Log.d("Debug", "JSONParser - cookieString: " + cookieString); // Get token is = entity.getContent(); // Build response BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); tokenString = sb.toString(); // Replace html tags with "" tokenString = tokenString.replaceAll("<.*?>", "").trim(); // Log.d("Debug", "API - Token: " + tokenString); } // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } catch (Exception e) { Log.i("Debug", "Exception " + e.toString()); } return new String[] { tokenString, cookieString }; }
From source file:com.lgallardo.youtorrentcontroller.JSONParser.java
public String getVersion() throws JSONParserStatusCodeException { String url = "about.html"; // if server is publish in a subfolder, fix url if (subfolder != null && !subfolder.equals("")) { url = subfolder + "/" + url; }/*from www .ja va2 s . c o m*/ String aboutHtml = null; String version = null; HttpResponse httpResponse; DefaultHttpClient httpclient; 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(hostname, port, 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); // set http parameters url = protocol + "://" + hostname + ":" + port + "/" + url; // Log.d("Debug", "URL: " + url); HttpGet httpget = new HttpGet(url); HttpResponse response = httpclient.execute(targetHost, httpget); HttpEntity entity = response.getEntity(); StatusLine statusLine = response.getStatusLine(); int mStatusCode = statusLine.getStatusCode(); // Log.d("Debug", "Version - mStatusCode: " + mStatusCode); if (mStatusCode == 200) { // Save API aboutHtml = EntityUtils.toString(response.getEntity()); String aboutStartText = "qBittorrent v"; String aboutEndText = " (Web UI)"; int aboutStart = aboutHtml.indexOf(aboutStartText); int aboutEnd = aboutHtml.indexOf(aboutEndText); if (aboutEnd == -1) { aboutEndText = " Web UI"; aboutEnd = aboutHtml.indexOf(aboutEndText); } if (aboutStart >= 0 && aboutEnd > aboutStart) { version = aboutHtml.substring(aboutStart + aboutStartText.length(), aboutEnd); } // Log.d("Debug", "Version - VersionString: " + version); } if (entity != null) { entity.consumeContent(); } // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } catch (Exception e) { // Log.i("APIVer", "Exception " + e.toString()); } if (version == null) { version = ""; } return version; }
From source file:com.lgallardo.qbittorrentclient.JSONParser.java
public JSONArray getJSONArrayFromUrl(String url) throws JSONParserStatusCodeException { // if server is published in a subfolder, fix url if (subfolder != null && !subfolder.equals("")) { url = subfolder + "/" + url; }//w ww.j a v a 2 s . c o m HttpResponse httpResponse; DefaultHttpClient httpclient; 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(hostname, port, protocol); httpclient = getNewHttpClient(); httpclient.setParams(httpParameters); try { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); httpclient.getCredentialsProvider().setCredentials(authScope, credentials); url = protocol + "://" + hostname + ":" + port + "/" + url; HttpGet httpget = new HttpGet(url); if (this.cookie != null) { httpget.setHeader("Cookie", this.cookie); } 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(); // Build JSON BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); jArray = new JSONArray(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } catch (UnsupportedEncodingException e) { } catch (ClientProtocolException e) { Log.e("JSON", "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("JSON", "IO: " + e.toString()); // e.printStackTrace(); throw new JSONParserStatusCodeException(TIMEOUT_ERROR); } catch (JSONParserStatusCodeException e) { throw new JSONParserStatusCodeException(e.getCode()); } catch (Exception e) { Log.e("JSON", "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 JSON String return jArray; }
From source file:com.lgallardo.qbittorrentclient.JSONParser.java
public String getNewCookie() throws JSONParserStatusCodeException { String url = "login"; // if server is publish in a subfolder, fix url if (subfolder != null && !subfolder.equals("")) { url = subfolder + "/" + url; }//from w ww. ja v a2 s.co m String cookieString = null; HttpResponse httpResponse; DefaultHttpClient httpclient; 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(hostname, port, 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); // // In order to pass the username and password we must set the pair name value List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("username", this.username)); nvps.add(new BasicNameValuePair("password", this.password)); httpget.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); HttpResponse response = httpclient.execute(targetHost, httpget); HttpEntity entity = response.getEntity(); StatusLine statusLine = response.getStatusLine(); int mStatusCode = statusLine.getStatusCode(); if (mStatusCode == 200) { // Save cookie List<Cookie> cookies = httpclient.getCookieStore().getCookies(); if (!cookies.isEmpty()) { cookieString = cookies.get(0).getName() + "=" + cookies.get(0).getValue() + "; domain=" + cookies.get(0).getDomain(); cookieString = cookies.get(0).getName() + "=" + cookies.get(0).getValue(); } } if (entity != null) { entity.consumeContent(); } // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } catch (Exception e) { Log.e("Debug", "Exception " + e.toString()); } if (cookieString == null) { cookieString = ""; } return cookieString; }
From source file:com.lgallardo.qbittorrentclient.JSONParser.java
public String getVersion() throws JSONParserStatusCodeException { String url = "about.html"; // if server is publish in a subfolder, fix url if (subfolder != null && !subfolder.equals("")) { url = subfolder + "/" + url; }/*from ww w .j a v a 2 s. co m*/ String aboutHtml = null; String version = null; HttpResponse httpResponse; DefaultHttpClient httpclient; 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(hostname, port, 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); // set http parameters url = protocol + "://" + hostname + ":" + port + "/" + url; // Log.d("Debug", "URL: " + url); HttpGet httpget = new HttpGet(url); HttpResponse response = httpclient.execute(targetHost, httpget); HttpEntity entity = response.getEntity(); StatusLine statusLine = response.getStatusLine(); int mStatusCode = statusLine.getStatusCode(); // Log.d("Debug", "Version - mStatusCode: " + mStatusCode); if (mStatusCode == 200) { // Save API aboutHtml = EntityUtils.toString(response.getEntity()); String aboutStartText = "qBittorrent v"; String aboutEndText = " (Web UI)"; int aboutStart = aboutHtml.indexOf(aboutStartText); int aboutEnd = aboutHtml.indexOf(aboutEndText); if (aboutEnd == -1) { aboutEndText = " Web UI"; aboutEnd = aboutHtml.indexOf(aboutEndText); } if (aboutStart >= 0 && aboutEnd > aboutStart) { version = aboutHtml.substring(aboutStart + aboutStartText.length(), aboutEnd); } // Log.d("Debug", "Version - VersionString: " + version); } // if (mStatusCode != 200) { // httpclient.getConnectionManager().shutdown(); // throw new JSONParserStatusCodeException(mStatusCode); // } // if (entity != null) { entity.consumeContent(); } // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } catch (Exception e) { // Log.i("APIVer", "Exception " + e.toString()); } if (version == null) { version = ""; } return version; }
From source file:com.lgallardo.youtorrentcontroller.JSONParser.java
public JSONObject getJSONFromUrl(String url) throws JSONParserStatusCodeException { // if server is publish in a subfolder, fix url if (subfolder != null && !subfolder.equals("")) { url = subfolder + "/" + url; }//from w w w . j a v a 2 s. c o m HttpResponse httpResponse; DefaultHttpClient httpclient; 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(httpParameters); // 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); // set http parameters url = protocol + "://" + hostname + ":" + port + "/" + url + token; // Log.d("Debug", "getJSONFromUrl - url: " + url); // Log.d("Debug", "getJSONFromUrl - cookie: " + cookie); HttpGet httpget = new HttpGet(url); if (this.cookie != null) { httpget.setHeader("Cookie", this.cookie); } 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(); // Build JSON BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); // try parse the string to a JSON object jObj = new JSONObject(json); } catch (JSONException e) { Log.e("Debug", "getJSONFromUrl - JSONException - Error parsing data " + e.toString()); } catch (UnsupportedEncodingException e) { Log.e("Debug", "getJSONFromUrl - UnsupportedEncodingException: " + e.toString()); } catch (ClientProtocolException e) { Log.e("Debug", "getJSONFromUrl - ClientProtocolException: " + e.toString()); e.printStackTrace(); } catch (IOException e) { Log.e("Debug", "getJSONFromUrl - IOException: " + 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", "getJSONFromUrl - 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 JSON String return jObj; }