private String readResult(HttpURLConnection urlConnection) throws WeiboException { InputStream is = null; BufferedReader buffer = null; BeeboApplication globalContext = BeeboApplication.getInstance(); String errorStr = globalContext.getString(R.string.timeout); globalContext = null; try { is = urlConnection.getInputStream(); String content_encode = urlConnection.getContentEncoding(); if (!TextUtils.isEmpty(content_encode) && content_encode.equals("gzip")) { is = new GZIPInputStream(is); } buffer = new BufferedReader(new InputStreamReader(is)); StringBuilder strBuilder = new StringBuilder(); String line; while ((line = buffer.readLine()) != null) { strBuilder.append(line); } // AppLogger.d("result=" + strBuilder.toString()); return strBuilder.toString(); } catch (IOException e) { e.printStackTrace(); throw new WeiboException(errorStr, e); } finally { Utility.closeSilently(is); Utility.closeSilently(buffer); urlConnection.disconnect(); } }
@Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { buildSummary(); if (key.equals(SettingActivity.LIST_AVATAR_MODE)) { String value = sharedPreferences.getString(key, "1"); if (value.equals("1")) SettingUtils.setEnableBigAvatar(false); if (value.equals("2")) SettingUtils.setEnableBigAvatar(true); if (value.equals("3")) { SettingUtils.setEnableBigAvatar(Utility.isWifi(getActivity())); } } if (key.equals(SettingActivity.LIST_PIC_MODE)) { String value = sharedPreferences.getString(key, "1"); if (value.equals("1")) { SettingUtils.setEnableBigPic(false); // listHighPicMode.setEnabled(false); } if (value.equals("2")) { SettingUtils.setEnableBigPic(true); // listHighPicMode.setEnabled(true); } if (value.equals("3")) { SettingUtils.setEnableBigPic(Utility.isWifi(getActivity())); // listHighPicMode.setEnabled(true); } } if (key.equals(SettingActivity.LIST_HIGH_PIC_MODE)) { BeeboApplication.getInstance().getBitmapCache().evictAll(); } }
@Override protected void onCancelled(Boolean aBoolean) { super.onCancelled(aBoolean); if (Utility.isAllNotNull(getActivity(), this.e)) { Toast.makeText(getActivity(), e.getError(), Toast.LENGTH_SHORT).show(); } }
public String doGet(String urlStr, Map<String, String> param) throws WeiboException { BeeboApplication globalContext = BeeboApplication.getInstance(); String errorStr = globalContext.getString(R.string.timeout); globalContext = null; InputStream is = null; try { StringBuilder urlBuilder = new StringBuilder(urlStr); urlBuilder.append("?").append(Utility.encodeUrl(param)); URL url = new URL(urlBuilder.toString()); AppLoggerUtils.d("get request" + url); Proxy proxy = getProxy(); HttpURLConnection urlConnection; if (proxy != null) { urlConnection = (HttpURLConnection) url.openConnection(proxy); } else { urlConnection = (HttpURLConnection) url.openConnection(); } urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(false); urlConnection.setConnectTimeout(CONNECT_TIMEOUT); urlConnection.setReadTimeout(READ_TIMEOUT); urlConnection.setRequestProperty("Connection", "Keep-Alive"); urlConnection.setRequestProperty("Charset", "UTF-8"); urlConnection.setRequestProperty("Accept-Encoding", "gzip, deflate"); urlConnection.connect(); return handleResponse(urlConnection); } catch (IOException e) { e.printStackTrace(); throw new WeiboException(errorStr, e); } }
private String handleError(HttpURLConnection urlConnection) throws WeiboException { String result = readError(urlConnection); String err = null; int errCode = 0; try { AppLoggerUtils.e("error=" + result); JSONObject json = new JSONObject(result); err = json.optString("error_description", ""); if (TextUtils.isEmpty(err)) { err = json.getString("error"); } errCode = json.getInt("error_code"); WeiboException exception = new WeiboException(); exception.setError_code(errCode); exception.setOriError(err); if (errCode == ErrorCode.EXPIRED_TOKEN || errCode == ErrorCode.INVALID_TOKEN) { Utility.showExpiredTokenDialogOrNotification(); } throw exception; } catch (JSONException e) { e.printStackTrace(); } return result; }
@Override protected boolean canSend() { boolean haveContent = !TextUtils.isEmpty(getEditTextView().getText().toString()); boolean haveToken = !TextUtils.isEmpty(token); int sum = Utility.length(getEditTextView().getText().toString()); int num = 140 - sum; boolean contentNumBelow140 = (num >= 0); if (haveContent && haveToken && contentNumBelow140) { return true; } else { if (!haveContent && !haveToken) { Toast.makeText( this, getString(R.string.content_cant_be_empty_and_dont_have_account), Toast.LENGTH_SHORT) .show(); } else if (!haveContent) { getEditTextView().setError(getString(R.string.content_cant_be_empty)); } else if (!haveToken) { Toast.makeText(this, getString(R.string.dont_have_account), Toast.LENGTH_SHORT).show(); } if (!contentNumBelow140) { getEditTextView().setError(getString(R.string.content_words_number_too_many)); } } return false; }
private void setListViewPositionFromPositionsCache() { Utility.setListViewSelectionFromTop( getListView(), timeLinePosition != null ? timeLinePosition.position : 0, timeLinePosition != null ? timeLinePosition.top : 0, new Runnable() { @Override public void run() { setListViewUnreadTipBar(timeLinePosition); } }); }
private void addNewDataAndRememberPosition(final CommentListBean newValue) { int initSize = getDataList().getSize(); if (getActivity() != null && newValue.getSize() > 0) { final boolean jumpToTop = getDataList().getSize() == 0; getDataList().addNewData(newValue); if (!jumpToTop) { int index = getListView().getFirstVisiblePosition(); getAdapter().notifyDataSetChanged(); int finalSize = getDataList().getSize(); final int positionAfterRefresh = index + finalSize - initSize + getListView().getHeaderViewsCount(); // use 1 px to show newMsgTipBar Utility.setListViewSelectionFromTop( getListView(), positionAfterRefresh, 1, new Runnable() { @Override public void run() { newMsgTipBar.setValue(newValue, false); } }); } else { newMsgTipBar.setValue(newValue, true); newMsgTipBar.clearAndReset(); getAdapter().notifyDataSetChanged(); getListView().setSelection(0); } CommentToMeTimeLineDBTask.asyncReplace(getDataList(), accountBean.getUid()); saveTimeLinePositionToDB(); } }
public String doPost(String urlAddress, Map<String, String> param) throws WeiboException { BeeboApplication globalContext = BeeboApplication.getInstance(); String errorStr = globalContext.getString(R.string.timeout); globalContext = null; try { URL url = new URL(urlAddress); Proxy proxy = getProxy(); HttpsURLConnection uRLConnection; if (proxy != null) { uRLConnection = (HttpsURLConnection) url.openConnection(proxy); } else { uRLConnection = (HttpsURLConnection) url.openConnection(); } uRLConnection.setDoInput(true); uRLConnection.setDoOutput(true); uRLConnection.setRequestMethod("POST"); uRLConnection.setUseCaches(false); uRLConnection.setConnectTimeout(CONNECT_TIMEOUT); uRLConnection.setReadTimeout(READ_TIMEOUT); uRLConnection.setInstanceFollowRedirects(false); uRLConnection.setRequestProperty("Connection", "Keep-Alive"); uRLConnection.setRequestProperty("Charset", "UTF-8"); uRLConnection.setRequestProperty("Accept-Encoding", "gzip, deflate"); uRLConnection.connect(); DataOutputStream out = new DataOutputStream(uRLConnection.getOutputStream()); out.write(Utility.encodeUrl(param).getBytes()); out.flush(); out.close(); return handleResponse(uRLConnection); } catch (IOException e) { e.printStackTrace(); throw new WeiboException(errorStr, e); } }
@Override protected void onListViewScrollStop() { super.onListViewScrollStop(); timeLinePosition = Utility.getCurrentPositionFromListView(getListView()); }
private void saveTimeLinePositionToDB() { timeLinePosition = Utility.getCurrentPositionFromListView(getListView()); timeLinePosition.newMsgIds = newMsgTipBar.getValues(); CommentToMeTimeLineDBTask.asyncUpdatePosition(timeLinePosition, accountBean.getUid()); }
public boolean doUploadFile( String urlStr, Map<String, String> param, String path, String imageParamName, final FileUploaderHttpHelper.ProgressListener listener) throws WeiboException { String BOUNDARYSTR = getBoundry(); File targetFile = new File(path); byte[] barry = null; int contentLength = 0; String sendStr = ""; try { barry = ("--" + BOUNDARYSTR + "--\r\n").getBytes("UTF-8"); sendStr = getBoundaryMessage( BOUNDARYSTR, param, imageParamName, new File(path).getName(), "image/png"); contentLength = sendStr.getBytes("UTF-8").length + (int) targetFile.length() + 2 * barry.length; } catch (UnsupportedEncodingException e) { } int totalSent = 0; String lenstr = Integer.toString(contentLength); HttpURLConnection urlConnection = null; BufferedOutputStream out = null; FileInputStream fis = null; BeeboApplication globalContext = BeeboApplication.getInstance(); String errorStr = globalContext.getString(R.string.timeout); globalContext = null; try { URL url = null; url = new URL(urlStr); Proxy proxy = getProxy(); if (proxy != null) { urlConnection = (HttpURLConnection) url.openConnection(proxy); } else { urlConnection = (HttpURLConnection) url.openConnection(); } urlConnection.setConnectTimeout(UPLOAD_CONNECT_TIMEOUT); urlConnection.setReadTimeout(UPLOAD_READ_TIMEOUT); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setRequestMethod("POST"); urlConnection.setUseCaches(false); urlConnection.setRequestProperty("Connection", "Keep-Alive"); urlConnection.setRequestProperty("Charset", "UTF-8"); urlConnection.setRequestProperty( "Content-type", "multipart/form-data;boundary=" + BOUNDARYSTR); urlConnection.setRequestProperty("Content-Length", lenstr); ((HttpURLConnection) urlConnection).setFixedLengthStreamingMode(contentLength); urlConnection.connect(); out = new BufferedOutputStream(urlConnection.getOutputStream()); out.write(sendStr.getBytes("UTF-8")); totalSent += sendStr.getBytes("UTF-8").length; fis = new FileInputStream(targetFile); int bytesRead; int bytesAvailable; int bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024; bytesAvailable = fis.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; bytesRead = fis.read(buffer, 0, bufferSize); long transferred = 0; final Thread thread = Thread.currentThread(); while (bytesRead > 0) { if (thread.isInterrupted()) { targetFile.delete(); throw new InterruptedIOException(); } out.write(buffer, 0, bufferSize); bytesAvailable = fis.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fis.read(buffer, 0, bufferSize); transferred += bytesRead; if (transferred % 50 == 0) { out.flush(); } if (listener != null) { listener.transferred(transferred); } } out.write(barry); totalSent += barry.length; out.write(barry); totalSent += barry.length; out.flush(); out.close(); if (listener != null) { listener.waitServerResponse(); } int status = urlConnection.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { String error = handleError(urlConnection); throw new WeiboException(error); } targetFile.delete(); } catch (IOException e) { e.printStackTrace(); throw new WeiboException(errorStr, e); } finally { Utility.closeSilently(fis); Utility.closeSilently(out); if (urlConnection != null) { urlConnection.disconnect(); } } return true; }
public boolean doGetSaveFile( String urlStr, String path, FileDownloaderHttpHelper.DownloadListener downloadListener) { File file = FileManager.createNewFileInSDCard(path); if (file == null) { return false; } boolean result = false; BufferedOutputStream out = null; InputStream in = null; HttpURLConnection urlConnection = null; try { URL url = new URL(urlStr); AppLoggerUtils.d("download request=" + urlStr); Proxy proxy = getProxy(); if (proxy != null) { urlConnection = (HttpURLConnection) url.openConnection(proxy); } else { urlConnection = (HttpURLConnection) url.openConnection(); } urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(false); urlConnection.setConnectTimeout(DOWNLOAD_CONNECT_TIMEOUT); urlConnection.setReadTimeout(DOWNLOAD_READ_TIMEOUT); urlConnection.setRequestProperty("Connection", "Keep-Alive"); urlConnection.setRequestProperty("Charset", "UTF-8"); urlConnection.setRequestProperty("Accept-Encoding", "gzip, deflate"); urlConnection.connect(); int status = urlConnection.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { return false; } int bytetotal = (int) urlConnection.getContentLength(); int bytesum = 0; int byteread = 0; out = new BufferedOutputStream(new FileOutputStream(file)); InputStream is = urlConnection.getInputStream(); String content_encode = urlConnection.getContentEncoding(); if (!TextUtils.isEmpty(content_encode) && content_encode.equals("gzip")) { is = new GZIPInputStream(is); } in = new BufferedInputStream(is); final Thread thread = Thread.currentThread(); byte[] buffer = new byte[1444]; while ((byteread = in.read(buffer)) != -1) { if (thread.isInterrupted()) { if (((float) bytesum / (float) bytetotal) < 0.8f) { file.delete(); throw new InterruptedIOException(); } } bytesum += byteread; out.write(buffer, 0, byteread); if (downloadListener != null && bytetotal > 0) { downloadListener.pushProgress(bytesum, bytetotal); } } if (downloadListener != null) { downloadListener.completed(); } AppLoggerUtils.v("download request= " + urlStr + " download finished"); result = true; } catch (IOException e) { e.printStackTrace(); AppLoggerUtils.v("download request= " + urlStr + " download failed"); } finally { Utility.closeSilently(in); Utility.closeSilently(out); if (urlConnection != null) { urlConnection.disconnect(); } } return result && ImageUtility.isThisBitmapCanRead(path); }