List of usage examples for org.apache.http.impl.client DefaultHttpClient setParams
public synchronized void setParams(final HttpParams params)
From source file:es.uma.lcc.tasks.PicturesViewTask.java
@Override public Void doInBackground(Void... args) { DefaultHttpClient httpclient = new DefaultHttpClient(); final HttpParams params = new BasicHttpParams(); HttpClientParams.setRedirecting(params, false); httpclient.setParams(params); String target = SERVERURL + "?" + QUERYSTRING_ACTION + "=" + ACTION_MYPICTURES; HttpGet httpget = new HttpGet(target); while (mCookie == null) mCookie = mMainActivity.getCurrentCookie(); httpget.setHeader("Cookie", mCookie.getName() + "=" + mMainActivity.getCurrentCookie().getValue()); try {// w w w. ja v a 2 s. c om HttpResponse response = httpclient.execute(httpget); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { throw new IOException("Invalid response from server: " + status.toString()); } HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = entity.getContent(); ByteArrayOutputStream content = new ByteArrayOutputStream(); // Read response into a buffered stream int readBytes = 0; byte[] sBuffer = new byte[256]; while ((readBytes = inputStream.read(sBuffer)) != -1) { content.write(sBuffer, 0, readBytes); } String result = new String(content.toByteArray()); try { JSONArray jsonArray = new JSONArray(result); if (jsonArray.length() == 0) { // should never happen Log.e(APP_TAG, LOG_ERROR + ": Malformed response from server"); } else { // Elements in a JSONArray keep their order JSONObject successState = jsonArray.getJSONObject(0); if (successState.get(JSON_RESULT).equals(JSON_RESULT_ERROR)) { if (successState.getBoolean(JSON_ISAUTHERROR) && mIsFirstRun) { mIsAuthError = true; } else { Log.e(APP_TAG, LOG_ERROR + ": Server found an error: " + successState.get("reason")); } } else { ArrayList<String> pics = new ArrayList<String>(); ArrayList<String> ids = new ArrayList<String>(); ArrayList<String> dates = new ArrayList<String>(); SimpleDateFormat oldFormat = new SimpleDateFormat(MISC_DATE_FORMAT, Locale.US); SimpleDateFormat newFormat = (SimpleDateFormat) java.text.SimpleDateFormat .getDateTimeInstance(); JSONObject obj; for (int i = 1; i < jsonArray.length(); i++) { obj = jsonArray.getJSONObject(i); Date d = oldFormat.parse(obj.getString(JSON_DATECREATED)); dates.add(newFormat.format(d)); pics.add(obj.getString(JSON_FILENAME)); ids.add(obj.getString(JSON_PICTUREID)); } Intent intent = new Intent(mMainActivity, PicturesViewActivity.class); intent.putStringArrayListExtra("pictures", pics); intent.putStringArrayListExtra("ids", ids); intent.putStringArrayListExtra("dates", dates); mMainActivity.startActivityForResult(intent, ACTIVITY_VIEW_MY_PICTURES); } } } catch (JSONException jsonEx) { Log.e(APP_TAG, LOG_ERROR + ": Malformed JSON response from server"); } catch (ParseException e) { // Will not happen: dates are sent by the server in a correct format Log.e(APP_TAG, LOG_ERROR + ": Malformed date sent by server"); } } else { // entity is null Log.e(APP_TAG, LOG_ERROR + ": null response from server"); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:swp.bibclient.Network.java
/** * Fragt bei einem Server nach den Medien an. * * @return Die Liste der Medien.//from ww w . j a v a 2 s .c o m * @throws IOException * Kann geworfen werden bei IO-Problemen. */ public final List<Medium> getMediums() throws IOException { DefaultHttpClient httpClient = new DefaultHttpClient(); // Setzen eines ConnectionTimeout von 2 Sekunden: HttpParams params = httpClient.getParams(); params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout); httpClient.setParams(params); // Der BibServer sollte lokal laufen, daher zugriff auf Localhost // 10.0.2.2 fr den AndroidEmulator. HttpContext localContext = new BasicHttpContext(); HttpGet httpGet = new HttpGet(server + mediumpath); String text = null; Log.i(Network.class.getName(), "Try to get a http connection..."); HttpResponse response = httpClient.execute(httpGet, localContext); HttpEntity entity = response.getEntity(); text = getASCIIContentFromEntity(entity); Log.i(Network.class.getName(), "Create new Gson object"); Gson gson = new Gson(); Log.i(Network.class.getName(), "Create listOfTestObject"); // Wir arbeiten mit einem TypeToken um fr eine generische Liste wieder // Objekte zu erhalten. Type listOfTestObject = new TypeToken<List<Medium>>() { }.getType(); Log.i(Network.class.getName(), "Convert to a list."); /* * Hier befindet sich ein unsicherer Cast, da wir nicht wirklich wissen, * ob der String, den wir von der Website bekommen, sich wirklich in * eine Liste von Bchern umwandeln lsst */ try { @SuppressWarnings("unchecked") List<Medium> list = Collections.synchronizedList((List<Medium>) gson.fromJson(text, listOfTestObject)); return list; } catch (ClassCastException e) { throw new ClientProtocolException("Returned type is not a list of book objects"); } }
From source file:es.uma.lcc.tasks.SendUpdateTask.java
@Override public Void doInBackground(Void... args) { DefaultHttpClient httpclient = new DefaultHttpClient(); final HttpParams params = new BasicHttpParams(); HttpClientParams.setRedirecting(params, false); httpclient.setParams(params); String target = SERVERURL + "?" + QUERYSTRING_ACTION + "=" + ACTION_UPDATE + "&" + QUERYSTRING_PICTUREID + "=" + mPicId; HttpPost httppost = new HttpPost(target); while (mCookie == null) mCookie = mMainActivity.getCurrentCookie(); httppost.setHeader("Cookie", mCookie.getName() + "=" + mCookie.getValue()); String jsonOperations = buildUpdateOperations(mOperations, mPicId); try {/* w ww. ja v a2 s . c om*/ StringEntity permissionsEntity = new StringEntity(jsonOperations); permissionsEntity.setContentType(new BasicHeader("Content-Type", "application/json")); httppost.setEntity(permissionsEntity); HttpResponse response = httpclient.execute(httppost); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { throw new IOException("Invalid response from server: " + status.toString()); } HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = entity.getContent(); ByteArrayOutputStream content = new ByteArrayOutputStream(); // Read response into a buffered stream int readBytes = 0; byte[] sBuffer = new byte[256]; while ((readBytes = inputStream.read(sBuffer)) != -1) { content.write(sBuffer, 0, readBytes); } String result = new String(content.toByteArray()); try { JSONArray jsonArray = new JSONArray(result); if (jsonArray.length() == 0) { // should never happen Log.e(APP_TAG, LOG_ERROR + ": Malformed response from server"); } else { // Elements in a JSONArray keep their order JSONObject successState = jsonArray.getJSONObject(0); if (successState.get(JSON_RESULT).equals(JSON_RESULT_ERROR)) { if (successState.getBoolean(JSON_ISAUTHERROR) && mIsFirstRun) { mIsAuthError = true; } else { Log.e(APP_TAG, LOG_ERROR + ": Server found an error: " + successState.get(JSON_REASON)); } } else {// result is ok, if there were modifications we notify the user if (mOperations != null && mOperations.size() > 0) mIsSuccessfulUpdate = true; } } } catch (JSONException jsonEx) { Log.e(APP_TAG, LOG_ERROR + ": Malformed JSON response from server"); } } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:es.uma.lcc.tasks.PictureDetailsTask.java
@Override public Void doInBackground(Void... args) { DefaultHttpClient httpclient = new DefaultHttpClient(); int width, height; final HttpParams params = new BasicHttpParams(); HttpClientParams.setRedirecting(params, false); httpclient.setParams(params); String target = SERVERURL + "?" + QUERYSTRING_ACTION + "=" + ACTION_PICTUREDETAILS + "&" + QUERYSTRING_PICTUREID + "=" + mPicId; HttpGet httpget = new HttpGet(target); while (mCookie == null) mCookie = mMainActivity.getCurrentCookie(); httpget.setHeader("Cookie", mCookie.getName() + "=" + mMainActivity.getCurrentCookie().getValue()); try {/*from w w w . ja v a 2 s . c o m*/ HttpResponse response = httpclient.execute(httpget); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { throw new IOException("Invalid response from server: " + status.toString()); } HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = entity.getContent(); ByteArrayOutputStream content = new ByteArrayOutputStream(); // Read response into a buffered stream int readBytes = 0; byte[] sBuffer = new byte[256]; while ((readBytes = inputStream.read(sBuffer)) != -1) { content.write(sBuffer, 0, readBytes); } String result = new String(content.toByteArray()); try { JSONArray jsonArray = new JSONArray(result); if (jsonArray.length() == 0) { // should never happen Log.e(APP_TAG, LOG_ERROR + ": Malformed response from server"); } else { // Elements in a JSONArray keep their order JSONObject successState = jsonArray.getJSONObject(0); if (successState.get(JSON_RESULT).equals(JSON_RESULT_ERROR)) { if (successState.getBoolean(JSON_ISAUTHERROR) && mIsFirstRun) { mIsAuthError = true; } else { Log.e(APP_TAG, LOG_ERROR + ": Server found an error: " + successState.get(JSON_REASON)); } } else { ArrayList<String> users = new ArrayList<String>(); ArrayList<String> coords = new ArrayList<String>(); ArrayList<String> ids = new ArrayList<String>(); JSONObject obj = jsonArray.getJSONObject(0); width = obj.getInt(JSON_IMGWIDTH); height = obj.getInt(JSON_IMGHEIGHT); for (int i = 1; i < jsonArray.length(); i++) { obj = jsonArray.getJSONObject(i); users.add(obj.getString(JSON_USERNAME)); coords.add(formatCoordinates(obj.getInt(JSON_HSTART), obj.getInt(JSON_HEND), obj.getInt(JSON_VSTART), obj.getInt(JSON_VEND))); ids.add(obj.getString(JSON_PERMISSIONID)); } Intent intent = new Intent(mMainActivity, PictureDetailsActivity.class); intent.putStringArrayListExtra("users", users); intent.putStringArrayListExtra("coordinates", coords); intent.putStringArrayListExtra("ids", ids); intent.putExtra("height", height); intent.putExtra("width", width); intent.putExtra("picId", mPicId); intent.putExtra("username", mMainActivity.getUserEmail()); mMainActivity.startActivityForResult(intent, ACTIVITY_PICTURE_DETAILS); } } } catch (JSONException jsonEx) { Log.e(APP_TAG, LOG_ERROR + ": Malformed JSON response from server"); } } else { // entity is null Log.e(APP_TAG, LOG_ERROR + ": null response from server"); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:es.uma.lcc.tasks.DecryptionRequestTask.java
public Void doInBackground(Void... parameters) { if (mPicId == null) { mDecodedBmp = BitmapFactory.decodeFile(mSrc); } else {/*from w w w .ja v a2 s . co m*/ DefaultHttpClient httpclient = new DefaultHttpClient(); final HttpParams params = new BasicHttpParams(); HttpClientParams.setRedirecting(params, false); httpclient.setParams(params); String target = SERVERURL + "?" + QUERYSTRING_ACTION + "=" + ACTION_READPERMISSIONS + "&" + QUERYSTRING_PICTUREID + "=" + mPicId; HttpGet httpget = new HttpGet(target); while (mCookie == null) // loop until authentication finishes, if necessary mCookie = mMainActivity.getCurrentCookie(); httpget.setHeader("Cookie", mCookie.getName() + "=" + mMainActivity.getCurrentCookie().getValue()); System.out.println("Cookie in header: " + mMainActivity.getCurrentCookie().getValue()); try { HttpResponse response = httpclient.execute(httpget); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { mConnectionSucceeded = false; throw new IOException("Invalid response from server: " + status.toString()); } HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = entity.getContent(); ByteArrayOutputStream content = new ByteArrayOutputStream(); // Read response into a buffered stream int readBytes = 0; byte[] sBuffer = new byte[256]; while ((readBytes = inputStream.read(sBuffer)) != -1) { content.write(sBuffer, 0, readBytes); } String result = new String(content.toByteArray()); try { JSONArray jsonArray = new JSONArray(result); JSONObject jsonObj; if (jsonArray.length() == 0) { // should never happen Log.e(APP_TAG, LOG_ERROR + ": Malformed response from server"); } else { // Elements in a JSONArray keep their order JSONObject successState = jsonArray.getJSONObject(0); if (successState.get(JSON_RESULT).equals(JSON_RESULT_ERROR)) { if (successState.getBoolean(JSON_ISAUTHERROR) && mIsFirstRun) { mIsAuthError = true; Log.e(APP_TAG, LOG_ERROR + ": Server found an auth error: " + successState.get(JSON_REASON)); } else { Log.e(APP_TAG, LOG_ERROR + ": Server found an error: " + successState.get(JSON_REASON)); } } else { mSquareNum = jsonArray.length() - 1; mHorizStarts = new int[mSquareNum]; mHorizEnds = new int[mSquareNum]; mVertStarts = new int[mSquareNum]; mVertEnds = new int[mSquareNum]; mKeys = new String[mSquareNum]; for (int i = 0; i < mSquareNum; i++) { jsonObj = jsonArray.getJSONObject(i + 1); mHorizStarts[i] = jsonObj.getInt(JSON_HSTART); mHorizEnds[i] = jsonObj.getInt(JSON_HEND); mVertStarts[i] = jsonObj.getInt(JSON_VSTART); mVertEnds[i] = jsonObj.getInt(JSON_VEND); mKeys[i] = jsonObj.getString(JSON_KEY); } publishProgress(10); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; // get dimensions without reloading the image BitmapFactory.decodeFile(mSrc, options); mWidth = options.outWidth; mHeight = options.outHeight; mDecodedBmp = Bitmap.createBitmap(options.outWidth, options.outHeight, Config.ARGB_8888); if (mSquareNum == 0) { mDecodedBmp = BitmapFactory.decodeFile(mSrc); } else { mHasFoundKeys = true; byte[] pixels = MainActivity.decodeWrapperRegions(mSrc, mSquareNum, mHorizStarts, mHorizEnds, mVertStarts, mVertEnds, mKeys, mPicId); /* Native side returns each pixel as an RGBA quadruplet, with each a C unsigned byte ([0,255]). However, Java reads those as signed bytes ([-128, 127]) in two's complement. We mask them with 0xFF to ensure most significant bits set to 0, therefore interpreting them as their positive (unsigned) value. Furthermore, Java functions take pixels in ARGB (and not RGBA), so we manually re-order them */ int baseIndex; for (int i = 0; i < mWidth; i++) { for (int j = 0; j < mHeight; j++) { baseIndex = 4 * (j * mWidth + i); mDecodedBmp.setPixel(i, j, Color.argb(pixels[baseIndex + 3] & 0xff, pixels[baseIndex] & 0xff, pixels[baseIndex + 1] & 0xff, pixels[baseIndex + 2] & 0xff)); } } } } } } catch (JSONException jsonEx) { Log.e(APP_TAG, LOG_ERROR + ": Malformed JSON response from server"); mSquareNum = 0; } } } catch (ClientProtocolException e) { mConnectionSucceeded = false; Log.e(APP_TAG, LOG_ERROR + ": " + e.getMessage()); } catch (IOException e) { mConnectionSucceeded = false; Log.e(APP_TAG, LOG_ERROR + ": " + e.getMessage()); } } return null; }
From source file:es.uma.lcc.tasks.EncryptionUploaderTask.java
@Override public String doInBackground(Void... voids) { String dst = null;// www.ja v a2s .c o m String filename = mSrc.substring(mSrc.lastIndexOf("/") + 1, mSrc.lastIndexOf(".")); ArrayList<Rectangle> rects = new ArrayList<Rectangle>(); for (String s : mRectangles) rects.add(new Rectangle(s)); mSquareNum = rects.size(); mHorizStarts = new int[mSquareNum]; mHorizEnds = new int[mSquareNum]; mVertStarts = new int[mSquareNum]; mVertEnds = new int[mSquareNum]; mKeys = new String[mSquareNum]; for (int i = 0; i < mSquareNum; i++) { mHorizStarts[i] = rects.get(i).x0 / 16; mHorizEnds[i] = rects.get(i).xEnd / 16; mVertStarts[i] = rects.get(i).y0 / 16; mVertEnds[i] = rects.get(i).yEnd / 16; } mNewId = null; boolean permissionToSelf = false; JSONArray permissions = new JSONArray(); try { JSONObject obj = new JSONObject(); JSONArray usernames; obj.put(JSON_PROTOCOLVERSION, CURRENT_VERSION); obj.put(JSON_FILENAME, filename); obj.put(JSON_IMGHEIGHT, mHeight); obj.put(JSON_IMGWIDTH, mWidth); permissions.put(obj); for (int i = 0; i < mSquareNum; i++) { TreeSet<String> auxSet = new TreeSet<String>(); // helps in checking a permission is not granted twice obj = new JSONObject(); obj.put(JSON_HSTART, mHorizStarts[i]); obj.put(JSON_HEND, mHorizEnds[i]); obj.put(JSON_VSTART, mVertStarts[i]); obj.put(JSON_VEND, mVertEnds[i]); usernames = new JSONArray(); usernames.put(mMainActivity.getUserEmail().toLowerCase(Locale.ENGLISH)); auxSet.add(mMainActivity.getUserEmail().toLowerCase(Locale.ENGLISH)); for (String str : rects.get(i).getPermissionsArrayList()) { if (!auxSet.contains(str.toLowerCase(Locale.ENGLISH))) { usernames.put(str.toLowerCase(Locale.ENGLISH)); auxSet.add(str.toLowerCase(Locale.ENGLISH)); } else if (str.equalsIgnoreCase(mMainActivity.getUserEmail())) permissionToSelf = true; } obj.put(JSON_USERNAME, usernames); permissions.put(obj); } } catch (JSONException jsonex) { // Will never happen: every value is either a number, or a correctly formatted email } if (permissionToSelf) { publishProgress(5); } DefaultHttpClient httpclient = new DefaultHttpClient(); final HttpParams params = new BasicHttpParams(); HttpClientParams.setRedirecting(params, false); httpclient.setParams(params); String target = SERVERURL + "?" + QUERYSTRING_ACTION + "=" + ACTION_ONESTEPUPLOAD; HttpPost httppost = new HttpPost(target); while (mCookie == null) { // loop until authentication finishes, if necessary mCookie = mMainActivity.getCurrentCookie(); } try { StringEntity permissionsEntity = new StringEntity(permissions.toString()); permissionsEntity.setContentType(new BasicHeader("Content-Type", "application/json")); httppost.setEntity(permissionsEntity); httppost.setHeader("Cookie", mCookie.getName() + "=" + mMainActivity.getCurrentCookie().getValue()); System.out.println("Cookie in header: " + mMainActivity.getCurrentCookie().getValue()); HttpResponse response = httpclient.execute(httppost); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { mConnectionSucceeded = false; throw new IOException("Invalid response from server: " + status.toString()); } HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = entity.getContent(); ByteArrayOutputStream content = new ByteArrayOutputStream(); // Read response into a buffered stream int readBytes = 0; byte[] sBuffer = new byte[256]; while ((readBytes = inputStream.read(sBuffer)) != -1) { content.write(sBuffer, 0, readBytes); } String result = new String(content.toByteArray()); try { JSONArray jsonArray = new JSONArray(result); if (jsonArray.length() == 0) { // should never happen Log.e(APP_TAG, LOG_ERROR + ": Malformed response from server"); mConnectionSucceeded = false; } else { // Elements in a JSONArray keep their order JSONObject successState = jsonArray.getJSONObject(0); if (successState.get(JSON_RESULT).equals(JSON_RESULT_ERROR)) { if (successState.getBoolean(JSON_ISAUTHERROR) && mIsFirstRun) { mIsAuthError = true; Log.e(APP_TAG, LOG_ERROR + ": Server found an auth error: " + successState.get(JSON_REASON)); } else { mConnectionSucceeded = false; Log.e(APP_TAG, LOG_ERROR + ": Server found an error: " + successState.get("reason")); } } else { // everything went OK mNewId = jsonArray.getJSONObject(1).getString(JSON_PICTUREID); for (int i = 0; i < mSquareNum; i++) { mKeys[i] = jsonArray.getJSONObject(i + 2).getString(JSON_KEY); } if (mNewId == null) { mConnectionSucceeded = false; Log.e(APP_TAG, "Encryption: Error connecting to server"); } else { publishProgress(10); String date = new SimpleDateFormat("yyyyMMddHHmmss", Locale.US).format(new Date()); File directory = new File( Environment.getExternalStorageDirectory() + "/" + APP_TAG); if (!directory.exists()) { directory.mkdir(); } dst = Environment.getExternalStorageDirectory() + "/" + APP_TAG + "/" + ENCRYPTED_FILE_PREFIX + filename + "_" + date + ".jpg"; mSuccess = MainActivity.encodeWrapperRegions(mSrc, dst, mSquareNum, mHorizStarts, mHorizEnds, mVertStarts, mVertEnds, mKeys, mNewId); addToGallery(dst); } } } } catch (JSONException jsonEx) { mConnectionSucceeded = false; Log.e(APP_TAG, LOG_ERROR + ": Malformed JSON response from server"); } } } catch (ClientProtocolException e) { mConnectionSucceeded = false; } catch (IOException e) { mConnectionSucceeded = false; } return dst; }
From source file:com.gsbabil.antitaintdroid.UtilityFunctions.java
public String httpSubmit(Map<String, String> data) { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(MyApp.HTTP_SUBMIT_URL); HttpResponse response = null;/*from w w w.jav a 2s . c om*/ String sResponse = ""; HttpParams myHttpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(myHttpParams, MyApp.TIMEOUT); HttpConnectionParams.setSoTimeout(myHttpParams, MyApp.TIMEOUT); httpClient.setParams(myHttpParams); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> entry : data.entrySet()) { nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); response = httpClient.execute(httpPost); BufferedReader reader = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), "UTF-8")); String line; while ((line = reader.readLine()) != null) { if (sResponse != null) { sResponse = sResponse.trim() + "\n" + line.trim(); } else { sResponse = line; } } Log.i(MyApp.TAG, sResponse); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { EntityUtils.consume(resEntity); } httpClient.getConnectionManager().shutdown(); } catch (Throwable e) { Log.i(MyApp.TAG, e.getMessage().toString()); } return sResponse.trim(); }
From source file:pt.aptoide.backupapps.data.webservices.ManagerDownloads.java
private void download(ViewDownload download, boolean overwriteCache) { ViewCache localCache = download.getCache(); ViewNotification notification = download.getNotification(); boolean resuming = false; String localPath = localCache.getLocalPath(); String remotePath = download.getRemotePath(); int targetBytes; FileOutputStream fileOutputStream = null; try {//www. j ava 2s. c o m fileOutputStream = new FileOutputStream(localPath, !overwriteCache); DefaultHttpClient httpClient = new DefaultHttpClient(); 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 = Constants.SERVER_CONNECTION_TIMEOUT; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = Constants.SERVER_READ_TIMEOUT; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); httpClient.setParams(httpParameters); HttpGet httpGet = new HttpGet(remotePath); Log.d("Aptoide-download", "downloading from: " + remotePath + " to: " + localPath); Log.d("Aptoide-download", "downloading with: " + getUserAgentString() + " private: " + download.isLoginRequired()); httpGet.setHeader("User-Agent", getUserAgentString()); String resumeLength = Long.toString(download.getCache().getFile().length()); int resumeLengthInt = Integer.parseInt(resumeLength); if (!overwriteCache) { if (resumeLengthInt > 0) { resuming = true; } Log.d("Aptoide-download", "downloading from [bytes]: " + resumeLength); httpGet.setHeader("Range", "bytes=" + resumeLength + "-"); notification.incrementProgress(resumeLengthInt); } if (download.isLoginRequired()) { URL url = new URL(remotePath); httpClient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()), new UsernamePasswordCredentials(download.getLogin().getUsername(), download.getLogin().getPassword())); } HttpResponse httpResponse = httpClient.execute(httpGet); if (httpResponse == null) { Log.d("Aptoide-ManagerDownloads", "Problem in network... retry..."); httpResponse = httpClient.execute(httpGet); if (httpResponse == null) { Log.d("Aptoide-ManagerDownloads", "Major network exception... Exiting!"); /*msg_al.arg1= 1; download_error_handler.sendMessage(msg_al);*/ if (!resuming) { managerCache.clearCache(download.getCache()); } throw new TimeoutException(); } } int httpStatusCode = httpResponse.getStatusLine().getStatusCode(); Log.d("Aptoide-download", "Server Response Status Code: " + httpStatusCode); switch (httpStatusCode) { case 401: fileOutputStream.close(); if (!resuming) { managerCache.clearCache(download.getCache()); } // download.setFailReason(EnumDownloadFailReason.TIMEOUT); throw new TimeoutException(httpStatusCode + " " + httpResponse.getStatusLine().getReasonPhrase()); case 403: fileOutputStream.close(); if (!resuming) { managerCache.clearCache(download.getCache()); } // download.setFailReason(EnumDownloadFailReason.IP_BLACKLISTED); throw new AptoideExceptionDownload( httpStatusCode + " " + httpResponse.getStatusLine().getReasonPhrase()); case 404: fileOutputStream.close(); if (!resuming) { managerCache.clearCache(download.getCache()); } // download.setFailReason(EnumDownloadFailReason.NOT_FOUND); throw new AptoideExceptionNotFound( httpStatusCode + " " + httpResponse.getStatusLine().getReasonPhrase()); case 416: fileOutputStream.close(); if (!resuming) { managerCache.clearCache(download.getCache()); } notification.setCompleted(true); // try { // downloadStatusClient.updateDownloadStatus(cache.hashCode(), download); // } catch (RemoteException e4) { // e4.printStackTrace(); // } return; default: Log.d("Aptoide-ManagerDownloads", "Download target size: " + notification.getProgressCompletionTarget()); // if(download.isSizeKnown()){ // targetBytes = download.getSize()*Constants.KBYTES_TO_BYTES; //TODO check if server sends kbytes or bytes // notification.setProgressCompletionTarget(targetBytes); // }else{ if (httpResponse.containsHeader("Content-Length") && resumeLengthInt != 0) { targetBytes = Integer.parseInt(httpResponse.getFirstHeader("Content-Length").getValue()); Log.d("Aptoide-ManagerDownloads", "targetBytes: " + targetBytes); // notification.setProgressCompletionTarget(targetBytes); } // } InputStream inputStream = null; if ((httpResponse.getEntity().getContentEncoding() != null) && (httpResponse.getEntity().getContentEncoding().getValue().equalsIgnoreCase("gzip"))) { Log.d("Aptoide-ManagerDownloads", "with gzip"); inputStream = new GZIPInputStream(httpResponse.getEntity().getContent()); } else { // Log.d("Aptoide-ManagerDownloads","No gzip"); inputStream = httpResponse.getEntity().getContent(); } byte data[] = new byte[8096]; int bytesRead; while ((bytesRead = inputStream.read(data, 0, 8096)) > 0) { notification.incrementProgress(bytesRead); fileOutputStream.write(data, 0, bytesRead); } Log.d("Aptoide-ManagerDownloads", "Download done! Name: " + notification.getActionsTargetName() + " localPath: " + localPath); notification.setCompleted(true); fileOutputStream.flush(); fileOutputStream.close(); inputStream.close(); if (localCache.hasMd5Sum()) { if (!getManagerCache().md5CheckOk(localCache)) { managerCache.clearCache(download.getCache()); throw new AptoideExceptionDownload("md5 check failed!"); } } return; } } catch (Exception e) { try { fileOutputStream.flush(); fileOutputStream.close(); } catch (Exception e1) { } e.printStackTrace(); if (notification.getNotificationType().equals(EnumNotificationTypes.GET_APP) && download.getCache().getFile().length() > 0) { notification.setCompleted(true); serviceData.scheduleInstallApp(notification.getTargetsHashid()); } throw new AptoideExceptionDownload(e); } }
From source file:com.lgallardo.qbittorrentclient.RSSFeedParser.java
public RSSFeed getRSSChannelInfo(String url) { // Parse url/*from ww w. java2 s . c om*/ Uri uri = Uri.parse(url); int event; String text = null; String torrent = null; boolean header = true; HttpResponse httpResponse; DefaultHttpClient httpclient; XmlPullParserFactory xmlFactoryObject; XmlPullParser xmlParser = null; 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); // Log.d("Debug", "Host: " + uri.getAuthority()); // Making HTTP request HttpHost targetHost = new HttpHost(uri.getAuthority()); // httpclient = new DefaultHttpClient(httpParameters); // httpclient = new DefaultHttpClient(); httpclient = getNewHttpClient(); httpclient.setParams(httpParameters); RSSFeed rssFeed = new RSSFeed(); 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 HttpGet httpget = new HttpGet(url); 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(); xmlFactoryObject = XmlPullParserFactory.newInstance(); xmlParser = xmlFactoryObject.newPullParser(); xmlParser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false); xmlParser.setInput(is, null); event = xmlParser.getEventType(); // Get Channel info String name; RSSFeedItem item = null; List<RSSFeedItem> items = new ArrayList<RSSFeedItem>(); // Get items while (event != XmlPullParser.END_DOCUMENT && header) { name = xmlParser.getName(); switch (event) { case XmlPullParser.START_TAG: if (name != null && name.equals("item")) { header = false; } break; case XmlPullParser.TEXT: text = xmlParser.getText(); break; case XmlPullParser.END_TAG: if (name.equals("title")) { if (header) { rssFeed.setChannelTitle(text); } } else if (name.equals("description")) { if (header) { } } else if (name.equals("link")) { if (header) { rssFeed.setChannelLink(text); } } break; } event = xmlParser.next(); } is.close(); } catch (Exception e) { Log.e("Debug", "RSSFeedParser - : " + 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 rssFeed; }
From source file:com.lgallardo.qbittorrentclient.RSSFeedParser.java
public RSSFeed getRSSFeed(String channelTitle, String channelUrl, String filter) { // Decode url link try {/*from w w w . j a va2 s . c om*/ channelUrl = URLDecoder.decode(channelUrl, "UTF-8"); } catch (UnsupportedEncodingException e) { Log.e("Debug", "RSSFeedParser - decoding error: " + e.toString()); } // Parse url Uri uri = uri = Uri.parse(channelUrl); ; int event; String text = null; String torrent = null; boolean header = true; // TODO delete itemCount, as it's not really used this.itemCount = 0; HttpResponse httpResponse; DefaultHttpClient httpclient; XmlPullParserFactory xmlFactoryObject; XmlPullParser xmlParser = null; 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); RSSFeed rssFeed = new RSSFeed(); rssFeed.setChannelTitle(channelTitle); rssFeed.setChannelLink(channelUrl); httpclient = null; try { // Making HTTP request HttpHost targetHost = new HttpHost(uri.getAuthority()); // httpclient = new DefaultHttpClient(httpParameters); // httpclient = new DefaultHttpClient(); httpclient = getNewHttpClient(); httpclient.setParams(httpParameters); // AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); // UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password); // // httpclient.getCredentialsProvider().setCredentials(authScope, credentials); // set http parameters HttpGet httpget = new HttpGet(channelUrl); 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(); xmlFactoryObject = XmlPullParserFactory.newInstance(); xmlParser = xmlFactoryObject.newPullParser(); xmlParser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false); xmlParser.setInput(is, null); event = xmlParser.getEventType(); // Get Channel info String name; RSSFeedItem item = null; ArrayList<RSSFeedItem> items = new ArrayList<RSSFeedItem>(); // Get items while (event != XmlPullParser.END_DOCUMENT) { name = xmlParser.getName(); switch (event) { case XmlPullParser.START_TAG: if (name != null && name.equals("item")) { header = false; item = new RSSFeedItem(); itemCount = itemCount + 1; } try { for (int i = 0; i < xmlParser.getAttributeCount(); i++) { if (xmlParser.getAttributeName(i).equals("url")) { torrent = xmlParser.getAttributeValue(i); if (torrent != null) { torrent = Uri.decode(URLEncoder.encode(torrent, "UTF-8")); } break; } } } catch (Exception e) { } break; case XmlPullParser.TEXT: text = xmlParser.getText(); break; case XmlPullParser.END_TAG: if (name.equals("title")) { if (!header) { item.setTitle(text); // Log.d("Debug", "PARSER - Title: " + text); } } else if (name.equals("description")) { if (header) { // Log.d("Debug", "Channel Description: " + text); } else { item.setDescription(text); // Log.d("Debug", "Description: " + text); } } else if (name.equals("link")) { if (!header) { item.setLink(text); // Log.d("Debug", "Link: " + text); } } else if (name.equals("pubDate")) { // Set item pubDate if (item != null) { item.setPubDate(text); } } else if (name.equals("enclosure")) { item.setTorrentUrl(torrent); // Log.d("Debug", "Enclosure: " + torrent); } else if (name.equals("item") && !header) { if (items != null & item != null) { // Fix torrent url for no-standard rss feeds if (torrent == null) { String link = item.getLink(); if (link != null) { link = Uri.decode(URLEncoder.encode(link, "UTF-8")); } item.setTorrentUrl(link); } items.add(item); } } break; } event = xmlParser.next(); // if (!header) { // items.add(item); // } } // Filter items // Log.e("Debug", "RSSFeedParser - filter: >" + filter + "<"); if (filter != null && !filter.equals("")) { Iterator iterator = items.iterator(); while (iterator.hasNext()) { item = (RSSFeedItem) iterator.next(); // If link doesn't match filter, remove it // Log.e("Debug", "RSSFeedParser - item no filter: >" + item.getTitle() + "<"); Pattern patter = Pattern.compile(filter); Matcher matcher = patter.matcher(item.getTitle()); // get a matcher object if (!(matcher.find())) { iterator.remove(); } } } rssFeed.setItems(items); rssFeed.setItemCount(itemCount); rssFeed.setChannelPubDate(items.get(0).getPubDate()); rssFeed.setResultOk(true); is.close(); } catch (Exception e) { Log.e("Debug", "RSSFeedParser - : " + e.toString()); rssFeed.setResultOk(false); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources if (httpclient != null) { httpclient.getConnectionManager().shutdown(); } } // return JSON String return rssFeed; }