5.4.1 示例代码

你可以通过下面的图表(图 5.4-1)找出你应该实现的 HTTP / HTTPS 通信类型。

5.4.1.md - 图1

当发送或接收敏感信息时,将使用 HTTPS 通信,因为其通信通道使用 SSL / TLS 加密。 以下敏感信息需要 HTTPS 通信。

  • Web 服务的登录 ID /密码。
  • 保持认证状态的信息(会话 ID,令牌,Cookie 等)
  • 取决于 Web 服务的重要/机密信息(个人信息,信用卡信息等)

具有网络通信的智能手机应用是“系统”和 Web 服务器的一部分。 而且你必须根据整个“系统”的安全设计和编码,为每个通信选择 HTTP 或 HTTPS。 表 5.4-1 用于比较 HTTP 和 HTTPS。 表 5.4-2 是示例代码的差异。

表 5.4-1 HTTP 与 HTTPS 通信方式的比较

HTTP HTTPS
特性 URL http://开头
加密内容
内容的篡改检测 不可能
对服务器进行认证 不可能
损害的风险 由攻击者读取内容
由攻击者修改内容
应用访问了伪造的服务器

表 5.4-2 HTTP/HTTPS 通信示例代码的解释

示例代码 通信 收发敏感信息 服务器证书
通过 HTTP 的通信 HTTP 不适用 -
通过 HTTPS 的通信 HTTPS OK 服务器证书由可信第三方机构签署,例如 Cybertrust 和 VeriSign
通过 HTTPS 使用私有证书的通信 HTTTPS OK 私有证书(经常能在内部服务器或测试服务器上看到的操作)

Android 支持java.net.HttpURLConnection / javax.net.ssl.HttpsURLConnection作为 HTTP / HTTPS 通信 API。 在 Android 6.0(API Level 23)版本中,另一个 HTTP 客户端库 Apache HttpClient 的支持已被删除。

5.4.1.1 通过 HTTP 进行通信

它基于两个前提,即通过 HTTP 通信发送/接收的所有内容都可能被攻击者嗅探和篡改,并且你的目标服务器可能被攻击者准备的假服务器替换。 只有在没有造成损害或损害在允许范围内的情况下,才能使用 HTTP 通信,即使在本地也是如此。 如果应用无法接受该前提,请参阅“5.4.1.2 通过 HTTPS 进行通信”和“5.4.1.3 通过 HTTPS 使用私有证书进行通信”。

以下示例代码显示了一个应用,它在 Web 服务器上执行图像搜索,获取结果图像并显示它。与服务器的 HTTP 通信在搜索时执行两次。第一次通信是搜索图像数据,第二次是获取它。它使用AsyncTask创建用于通信过程的工作线程,来避免在 UI 线程上执行通信。与服务器的通信中发送/接收的内容,在这里不被认为是敏感的(例如,用于搜索的字符串,图像的 URL 或图像数据)。因此,接收到的数据,如图像的 URL 和图像数据,可能由攻击者提供。为了简单地显示示例代码,在示例代码中没有采取任何对策,通过将接收到的攻击数据视为可容忍的。此外,在 JSON 解析或显示图像数据期间,可能出现异常的处理将被忽略。根据应用规范,有必要正确处理例外情况。

要点:

  1. 发送的数据中不得包含敏感信息。
  2. 假设收到的数据可能来自攻击者。

HttpImageSearch.java

  1. package org.jssec.android.https.imagesearch;
  2. import android.os.AsyncTask;
  3. import org.json.JSONException;
  4. import org.json.JSONObject;
  5. import java.io.BufferedInputStream;
  6. import java.io.ByteArrayOutputStream;
  7. import java.io.IOException;
  8. import java.net.HttpURLConnection;
  9. import java.net.URL;
  10. public abstract class HttpImageSearch extends AsyncTask<String, Void, Object> {
  11. @Override
  12. protected Object doInBackground(String... params) {
  13. byte[] responseArray;
  14. // --------------------------------------------------------
  15. // Communication 1st time: Execute image search
  16. // --------------------------------------------------------
  17. // *** POINT 1 *** Sensitive information must not be contained in send data.
  18. // Send image search character string
  19. StringBuilder s = new StringBuilder();
  20. for (String param : params){
  21. s.append(param);
  22. s.append('+');
  23. }
  24. s.deleteCharAt(s.length() - 1);
  25. String search_url = "http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=" +
  26. s.toString();
  27. responseArray = getByteArray(search_url);
  28. if (responseArray == null) {
  29. return null;
  30. }
  31. // *** POINT 2 *** Suppose that received data may be sent from attackers.
  32. // This is sample, so omit the process in case of the searching result is the data from an attacker.
  33. // This is sample, so omit the exception process in case of JSON purse.
  34. String image_url;
  35. try {
  36. String json = new String(responseArray);
  37. image_url = new JSONObject(json).getJSONObject("responseData")
  38. .getJSONArray("results").getJSONObject(0).getString("url");
  39. } catch(JSONException e) {
  40. return e;
  41. }
  42. // --------------------------------------------------------
  43. // Communication 2nd time: Get images
  44. // --------------------------------------------------------
  45. // *** POINT 1 *** Sensitive information must not be contained in send data.
  46. if (image_url != null ) {
  47. responseArray = getByteArray(image_url);
  48. if (responseArray == null) {
  49. return null;
  50. }
  51. }
  52. // *** POINT 2 *** Suppose that received data may be sent from attackers.
  53. return responseArray;
  54. }
  55. private byte[] getByteArray(String strUrl) {
  56. byte[] buff = new byte[1024];
  57. byte[] result = null;
  58. HttpURLConnection response;
  59. BufferedInputStream inputStream = null;
  60. ByteArrayOutputStream responseArray = null;
  61. int length;
  62. try {
  63. URL url = new URL(strUrl);
  64. response = (HttpURLConnection) url.openConnection();
  65. response.setRequestMethod("GET");
  66. response.connect();
  67. checkResponse(response);
  68. inputStream = new BufferedInputStream(response.getInputStream());
  69. responseArray = new ByteArrayOutputStream();
  70. while ((length = inputStream.read(buff)) != -1) {
  71. if (length > 0) {
  72. responseArray.write(buff, 0, length);
  73. }
  74. }
  75. result = responseArray.toByteArray();
  76. } catch (IOException e) {
  77. e.printStackTrace();
  78. } finally {
  79. if (inputStream != null) {
  80. try {
  81. inputStream.close();
  82. } catch (IOException e) {
  83. // This is sample, so omit the exception process
  84. }
  85. }
  86. if (responseArray != null) {
  87. try {
  88. responseArray.close();
  89. } catch (IOException e) {
  90. // This is sample, so omit the exception process
  91. }
  92. }
  93. }
  94. return result;
  95. }
  96. private void checkResponse(HttpURLConnection response) throws IOException {
  97. int statusCode = response.getResponseCode();
  98. if (HttpURLConnection.HTTP_OK != statusCode) {
  99. throw new IOException("HttpStatus: " + statusCode);
  100. }
  101. }
  102. }

ImageSearchActivity.java

  1. package org.jssec.android.https.imagesearch;
  2. import android.app.Activity;
  3. import android.graphics.Bitmap;
  4. import android.graphics.BitmapFactory;
  5. import android.os.AsyncTask;
  6. import android.os.Bundle;
  7. import android.view.View;
  8. import android.widget.EditText;
  9. import android.widget.ImageView;
  10. import android.widget.TextView;
  11. public class ImageSearchActivity extends Activity {
  12. private EditText mQueryBox;
  13. private TextView mMsgBox;
  14. private ImageView mImgBox;
  15. private AsyncTask<String, Void, Object> mAsyncTask ;
  16. @Override
  17. public void onCreate(Bundle savedInstanceState) {
  18. super.onCreate(savedInstanceState);
  19. setContentView(R.layout.activity_main);
  20. mQueryBox = (EditText)findViewById(R.id.querybox);
  21. mMsgBox = (TextView)findViewById(R.id.msgbox);
  22. mImgBox = (ImageView)findViewById(R.id.imageview);
  23. }
  24. @Override
  25. protected void onPause() {
  26. // After this, Activity may be deleted, so cancel the asynchronization process in advance.
  27. if (mAsyncTask != null) mAsyncTask.cancel(true);
  28. super.onPause();
  29. }
  30. public void onHttpSearchClick(View view) {
  31. String query = mQueryBox.getText().toString();
  32. mMsgBox.setText("HTTP:" + query);
  33. mImgBox.setImageBitmap(null);
  34. // Cancel, since the last asynchronous process might not have been finished yet.
  35. if (mAsyncTask != null) mAsyncTask.cancel(true);
  36. // Since cannot communicate by UI thread, communicate by worker thread by AsynchTask.
  37. mAsyncTask = new HttpImageSearch() {
  38. @Override
  39. protected void onPostExecute(Object result) {
  40. // Process the communication result by UI thread.
  41. if (result == null) {
  42. mMsgBox.append("¥nException occurs¥n");
  43. } else if (result instanceof Exception) {
  44. Exception e = (Exception)result;
  45. mMsgBox.append("¥nException occurs¥n" + e.toString());
  46. } else {
  47. // Exception process when image display is omitted here, since it's sample.
  48. byte[] data = (byte[])result;
  49. Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
  50. mImgBox.setImageBitmap(bmp);
  51. }
  52. }
  53. }.execute(query);
  54. // pass search character string and start asynchronous process
  55. }
  56. public void onHttpsSearchClick(View view) {
  57. String query = mQueryBox.getText().toString();
  58. mMsgBox.setText("HTTPS:" + query);
  59. mImgBox.setImageBitmap(null);
  60. // Cancel, since the last asynchronous process might not have been finished yet.
  61. if (mAsyncTask != null) mAsyncTask.cancel(true);
  62. // Since cannot communicate by UI thread, communicate by worker thread by AsynchTask.
  63. mAsyncTask = new HttpsImageSearch() {
  64. @Override
  65. protected void onPostExecute(Object result) {
  66. // Process the communication result by UI thread.
  67. if (result instanceof Exception) {
  68. Exception e = (Exception)result;
  69. mMsgBox.append("¥nException occurs¥n" + e.toString());
  70. } else {
  71. byte[] data = (byte[])result;
  72. Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
  73. mImgBox.setImageBitmap(bmp);
  74. }
  75. }
  76. }.execute(query);
  77. // pass search character string and start asynchronous process
  78. }
  79. }

AndroidManifest.xml

  1. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  2. package="org.jssec.android.https.imagesearch"
  3. android:versionCode="1"
  4. android:versionName="1.0">
  5. <uses-permission android:name="android.permission.INTERNET"/>
  6. <application
  7. android:icon="@drawable/ic_launcher"
  8. android:allowBackup="false"
  9. android:label="@string/app_name" >
  10. <activity
  11. android:name=".ImageSearchActivity"
  12. android:label="@string/app_name"
  13. android:theme="@android:style/Theme.Light"
  14. android:exported="true" >
  15. <intent-filter>
  16. <action android:name="android.intent.action.MAIN" />
  17. <category android:name="android.intent.category.LAUNCHER" />
  18. </intent-filter>
  19. </activity>
  20. </application>
  21. </manifest>

5.4.1.2 使用 HTTPS 进行通信

在 HTTPS 通信中,检查服务器是否可信,以及传输的数据是否加密。 为了验证服务器,Android HTTPS 库验证“服务器证书”,它在 HTTPS 事务的握手阶段从服务器传输,其要点如下:

  • 服务器证书由可信的第三方证书机构签署
  • 服务器证书的期限和其他属性有效
  • 服务器的主机名匹配服务器证书的主题字段中的 CN(通用名称)或 SAN(主题备用名称)

如果上述验证失败,则会引发SSLException(服务器证书验证异常)。 这可能意味着中间人攻击或服务器证书缺陷。 你的应用必须根据应用规范,以适当的顺序处理异常。

下一个示例代码用于 HTTPS 通信,它使用可信的第三方证书机构颁发的服务器证书连接到 Web 服务器。 对于使用私有服务器证书的 HTTPS 通信,请参阅“5.4.1.3 通过 HTTPS 使用私有证书进行通信”。

以下示例代码展示了一个应用,它在 Web 服务器上执行图像搜索,获取结果图像并显示它。 与服务器的 HTTPS 通信在搜索时执行两次。 第一次通信是搜索图像数据,第二次是获取它。 它使用AsyncTask创建用于通信过程的工作线程,来避免在 UI 线程上执行通信。 与服务器的通信中发送/接收的所有内容,在这里被认为是敏感的(例如,用于搜索的字符串,图像的 URL 或图像数据)。 为了简单地显示示例代码,不会执行针对SSLException的特殊处理。 根据应用规范,有必要正确处理异常。 另外,下面的示例代码允许使用 SSLv3 进行通信。 通常,我们建议配置远程服务器上的设置来禁用 SSLv3,以避免针对 SSLv3 中的漏洞(称为 POODLE)的攻击。

要点:

  1. URI 以https://开头。
  2. 发送数据中可能包含敏感信息。
  3. 尽管数据是从通过 HTTPS 连接的服务器发送的,但要小心并安全地处理收到的数据。
  4. SSLException应该在应用中以适当的顺序处理。

HttpsImageSearch.java

  1. package org.jssec.android.https.imagesearch;
  2. import org.json.JSONException;
  3. import org.json.JSONObject;
  4. import android.os.AsyncTask;
  5. import java.io.BufferedInputStream;
  6. import java.io.ByteArrayOutputStream;
  7. import java.io.IOException;
  8. import java.net.HttpURLConnection;
  9. import java.net.URL;
  10. public abstract class HttpsImageSearch extends AsyncTask<String, Void, Object> {
  11. @Override
  12. protected Object doInBackground(String... params) {
  13. byte[] responseArray;
  14. // --------------------------------------------------------
  15. // Communication 1st time : Execute image search
  16. // --------------------------------------------------------
  17. // *** POINT 1 *** URI starts with https://.
  18. // *** POINT 2 *** Sensitive information may be contained in send data.
  19. StringBuilder s = new StringBuilder();
  20. for (String param : params){
  21. s.append(param);
  22. s.append('+');
  23. }
  24. s.deleteCharAt(s.length() - 1);
  25. String search_url = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=" +
  26. s.toString();
  27. responseArray = getByteArray(search_url);
  28. if (responseArray == null) {
  29. return null;
  30. }
  31. // *** POINT 3 *** Handle the received data carefully and securely,
  32. // even though the data was sent from the server connected by HTTPS.
  33. // Omitted, since this is a sample. Please refer to "3.2 Handling Input Data Carefully and Securely."
  34. String image_url;
  35. try {
  36. String json = new String(responseArray);
  37. image_url = new JSONObject(json).getJSONObject("responseData")
  38. .getJSONArray("results").getJSONObject(0).getString("url");
  39. } catch(JSONException e) {
  40. return e;
  41. }
  42. // --------------------------------------------------------
  43. // Communication 2nd time : Get image
  44. // --------------------------------------------------------
  45. // *** POINT 1 *** URI starts with https://.
  46. // *** POINT 2 *** Sensitive information may be contained in send data.
  47. if (image_url != null ) {
  48. responseArray = getByteArray(image_url);
  49. if (responseArray == null) {
  50. return null;
  51. }
  52. }
  53. return responseArray;
  54. }
  55. private byte[] getByteArray(String strUrl) {
  56. byte[] buff = new byte[1024];
  57. byte[] result = null;
  58. HttpURLConnection response;
  59. BufferedInputStream inputStream = null;
  60. ByteArrayOutputStream responseArray = null;
  61. int length;
  62. try {
  63. URL url = new URL(strUrl);
  64. response = (HttpURLConnection) url.openConnection();
  65. response.setRequestMethod("GET");
  66. response.connect();
  67. checkResponse(response);
  68. inputStream = new BufferedInputStream(response.getInputStream());
  69. responseArray = new ByteArrayOutputStream();
  70. while ((length = inputStream.read(buff)) != -1) {
  71. if (length > 0) {
  72. responseArray.write(buff, 0, length);
  73. }
  74. }
  75. result = responseArray.toByteArray();
  76. } catch (IOException e) {
  77. e.printStackTrace();
  78. } finally {
  79. if (inputStream != null) {
  80. try {
  81. inputStream.close();
  82. } catch (IOException e) {
  83. // This is sample, so omit the exception process
  84. }
  85. }
  86. if (responseArray != null) {
  87. try {
  88. responseArray.close();
  89. } catch (IOException e) {
  90. // This is sample, so omit the exception process
  91. }
  92. }
  93. }
  94. return result;
  95. }
  96. private void checkResponse(HttpURLConnection response) throws IOException {
  97. int statusCode = response.getResponseCode();
  98. if (HttpURLConnection.HTTP_OK != statusCode) {
  99. throw new IOException("HttpStatus: " + statusCode);
  100. }
  101. }
  102. }

其他示例代码文件与“5.4.1.1 通过 HTTP 进行通信”相同,因此请参阅“5.4.1.1 通过 HTTP 进行通信”。

5.4.1.3 使用私有证书通过 HTTPS 进行通信

这部分展示了一个 HTTPS 通信的示例代码,其中包含私人颁发的服务器证书(私有证书),但不是可信的第三方机构颁发的服务器证书。 请参阅“5.4.3.1 如何创建私有证书并配置服务器”,来创建私有证书机构和私有证书的根证书,并在 Web 服务器中设置 HTTPS。 示例程序的资产中包含cacert.crt文件。 它是私有证书机构的根证书文件。

以下示例代码展示了一个应用,在 Web 服务器上获取图像并显示该图像。 HTTPS 用于与服务器的通信。 它使用AsyncTask创建用于通信过程的工作线程,来避免在 UI 线程上执行通信。 与服务器的通信中发送/接收的所有内容(图像的 URL 和图像数据)都被认为是敏感的。 为了简单地显示示例代码,不会执行针对SSLException的特殊处理。 根据应用规范,有必要正确处理异常。

要点:

  1. 使用私人证书机构的根证书来验证服务器证书。
  2. URI 以https://开头。
  3. 发送数据中可能包含敏感信息。
  4. 接收的数据可以像服务器一样被信任。
  5. SSLException应该在应用中以适当的顺序处理。

PrivateCertificathettpsGet.java

  1. package org.jssec.android.https.privatecertificate;
  2. import java.io.BufferedInputStream;
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.IOException;
  5. import java.net.HttpURLConnection;
  6. import java.net.URL;
  7. import java.security.KeyStore;
  8. import java.security.SecureRandom;
  9. import javax.net.ssl.HostnameVerifier;
  10. import javax.net.ssl.HttpsURLConnection;
  11. import javax.net.ssl.SSLContext;
  12. import javax.net.ssl.SSLException;
  13. import javax.net.ssl.SSLSession;
  14. import javax.net.ssl.TrustManagerFactory;
  15. import android.content.Context;
  16. import android.os.AsyncTask;
  17. public abstract class PrivateCertificateHttpsGet extends AsyncTask<String, Void, Object> {
  18. private Context mContext;
  19. public PrivateCertificateHttpsGet(Context context) {
  20. mContext = context;
  21. }
  22. @Override
  23. protected Object doInBackground(String... params) {
  24. TrustManagerFactory trustManager;
  25. BufferedInputStream inputStream = null;
  26. ByteArrayOutputStream responseArray = null;
  27. byte[] buff = new byte[1024];
  28. int length;
  29. try {
  30. URL url = new URL(params[0]);
  31. // *** POINT 1 *** Verify a server certificate with the root certificate of a private certificate authority.
  32. // Set keystore which includes only private certificate that is stored in assets, to client.
  33. KeyStore ks = KeyStoreUtil.getEmptyKeyStore();
  34. KeyStoreUtil.loadX509Certificate(ks,
  35. mContext.getResources().getAssets().open("cacert.crt"));
  36. // *** POINT 2 *** URI starts with https://.
  37. // *** POINT 3 *** Sensitive information may be contained in send data.
  38. trustManager = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  39. trustManager.init(ks);
  40. SSLContext sslCon = SSLContext.getInstance("TLS");
  41. sslCon.init(null, trustManager.getTrustManagers(), new SecureRandom());
  42. HttpURLConnection con = (HttpURLConnection)url.openConnection();
  43. HttpsURLConnection response = (HttpsURLConnection)con;
  44. response.setDefaultSSLSocketFactory(sslCon.getSocketFactory());
  45. response.setSSLSocketFactory(sslCon.getSocketFactory());
  46. checkResponse(response);
  47. // *** POINT 4 *** Received data can be trusted as same as the server.
  48. inputStream = new BufferedInputStream(response.getInputStream());
  49. responseArray = new ByteArrayOutputStream();
  50. while ((length = inputStream.read(buff)) != -1) {
  51. if (length > 0) {
  52. responseArray.write(buff, 0, length);
  53. }
  54. }
  55. return responseArray.toByteArray();
  56. } catch(SSLException e) {
  57. // *** POINT 5 *** SSLException should be handled with an appropriate sequence in an application.
  58. // Exception process is omitted here since it's sample.
  59. return e;
  60. } catch(Exception e) {
  61. return e;
  62. } finally {
  63. if (inputStream != null) {
  64. try {
  65. inputStream.close();
  66. } catch (Exception e) {
  67. // This is sample, so omit the exception process
  68. }
  69. }
  70. if (responseArray != null) {
  71. try {
  72. responseArray.close();
  73. } catch (Exception e) {
  74. // This is sample, so omit the exception process
  75. }
  76. }
  77. }
  78. }
  79. private void checkResponse(HttpURLConnection response) throws IOException {
  80. int statusCode = response.getResponseCode();
  81. if (HttpURLConnection.HTTP_OK != statusCode) {
  82. throw new IOException("HttpStatus: " + statusCode);
  83. }
  84. }
  85. }

KeyStoreUtil.java

  1. package org.jssec.android.https.privatecertificate;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.security.KeyStore;
  5. import java.security.KeyStoreException;
  6. import java.security.NoSuchAlgorithmException;
  7. import java.security.cert.Certificate;
  8. import java.security.cert.CertificateException;
  9. import java.security.cert.CertificateFactory;
  10. import java.security.cert.X509Certificate;
  11. import java.util.Enumeration;
  12. public class KeyStoreUtil {
  13. public static KeyStore getEmptyKeyStore() throws KeyStoreException,
  14. NoSuchAlgorithmException, CertificateException, IOException {
  15. KeyStore ks = KeyStore.getInstance("BKS");
  16. ks.load(null);
  17. return ks;
  18. }
  19. public static void loadAndroidCAStore(KeyStore ks)
  20. throws KeyStoreException, NoSuchAlgorithmException,
  21. CertificateException, IOException {
  22. KeyStore aks = KeyStore.getInstance("AndroidCAStore");
  23. aks.load(null);
  24. Enumeration<String> aliases = aks.aliases();
  25. while (aliases.hasMoreElements()) {
  26. String alias = aliases.nextElement();
  27. Certificate cert = aks.getCertificate(alias);
  28. ks.setCertificateEntry(alias, cert);
  29. }
  30. }
  31. public static void loadX509Certificate(KeyStore ks, InputStream is)
  32. throws CertificateException, KeyStoreException {
  33. try {
  34. CertificateFactory factory = CertificateFactory.getInstance("X509");
  35. X509Certificate x509 = (X509Certificate)factory.generateCertificate(is);
  36. String alias = x509.getSubjectDN().getName();
  37. ks.setCertificateEntry(alias, x509);
  38. } finally {
  39. try { is.close(); } catch (IOException e) { /* This is sample, so omit the exception process
  40. */ }
  41. }
  42. }
  43. }

PrivateCertificateHttpsActivity.java

  1. package org.jssec.android.https.privatecertificate;
  2. import android.app.Activity;
  3. import android.graphics.Bitmap;
  4. import android.graphics.BitmapFactory;
  5. import android.os.AsyncTask;
  6. import android.os.Bundle;
  7. import android.view.View;
  8. import android.widget.EditText;
  9. import android.widget.ImageView;
  10. import android.widget.TextView;
  11. public class PrivateCertificateHttpsActivity extends Activity {
  12. private EditText mUrlBox;
  13. private TextView mMsgBox;
  14. private ImageView mImgBox;
  15. private AsyncTask<String, Void, Object> mAsyncTask ;
  16. @Override
  17. public void onCreate(Bundle savedInstanceState) {
  18. super.onCreate(savedInstanceState);
  19. setContentView(R.layout.activity_main);
  20. mUrlBox = (EditText)findViewById(R.id.urlbox);
  21. mMsgBox = (TextView)findViewById(R.id.msgbox);
  22. mImgBox = (ImageView)findViewById(R.id.imageview);
  23. }
  24. @Override
  25. protected void onPause() {
  26. // After this, Activity may be discarded, so cancel asynchronous process in advance.
  27. if (mAsyncTask != null) mAsyncTask.cancel(true);
  28. super.onPause();
  29. }
  30. public void onClick(View view) {
  31. String url = mUrlBox.getText().toString();
  32. mMsgBox.setText(url);
  33. mImgBox.setImageBitmap(null);
  34. // Cancel, since the last asynchronous process might have not been finished yet.
  35. if (mAsyncTask != null) mAsyncTask.cancel(true);
  36. // Since cannot communicate through UI thread, communicate by worker thread by AsynchTask.
  37. mAsyncTask = new PrivateCertificateHttpsGet(this) {
  38. @Override
  39. protected void onPostExecute(Object result) {
  40. // Process the communication result through UI thread.
  41. if (result instanceof Exception) {
  42. Exception e = (Exception)result;
  43. mMsgBox.append("¥nException occurs¥n" + e.toString());
  44. } else {
  45. byte[] data = (byte[])result;
  46. Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
  47. mImgBox.setImageBitmap(bmp);
  48. }
  49. }
  50. }.execute(url);
  51. // Pass URL and start asynchronization process
  52. }
  53. }