Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.joythis.android.minimalhttps;
- import androidx.appcompat.app.AppCompatActivity;
- import android.content.Context;
- import android.os.AsyncTask;
- import android.os.Bundle;
- import android.widget.TextView;
- import javax.net.ssl.HttpsURLConnection;
- public class MainActivity extends AppCompatActivity {
- class MyAsyncTask extends AsyncTask
- <
- String//input data type (URL)
- ,
- Void //progress data type
- ,
- String //result data type (remote content)
- >
- {
- String mStrRemoteContent;
- //CTRL+O Override
- /*
- automatically called by the Android framework
- immediately before starting the execution of the task
- coded in doInBackground
- */
- @Override
- protected void onPreExecute() {
- super.onPreExecute();
- mStrRemoteContent = "";
- mTvRemoteContent.setText("Loading...");
- }//onPreExecute
- /*
- here is where we should write the code
- that will run on its own thread
- and asynchronously
- */
- @Override
- protected String doInBackground(
- String... strings //variable number of args of String datatype
- )
- {
- String strUrl = strings[0];
- mStrRemoteContent = "";
- /*
- mStrRemoteContent = AmHttp.consumeHttpsAtUrl(
- strUrl
- );
- */
- mStrRemoteContent = AmHttp.consumeHttpAtUrl(
- strUrl
- );
- //raw consumption until this point
- //return null;
- return mStrRemoteContent;
- }//doInBackground
- /*
- automatically called when
- doInBackground completes
- */
- @Override
- protected void onPostExecute(String s) {
- super.onPostExecute(s);
- /*
- the remote content has been loaded
- and will now be displayed in the TextView
- */
- /*
- opportunity to process the raw data
- */
- String strProcessingResult = processRawData(s);
- //mTvRemoteContent.setText(s);
- mTvRemoteContent.setText(strProcessingResult);
- }//onPostExecute
- }//MyAsyncTask
- private String processRawData(String pStrRawData){
- String strProcessingResult = "";
- String[] aRecordContactsFromRawData =
- pStrRawData.split("\n");
- for (String strContact : aRecordContactsFromRawData){
- String[] aParts = strContact.split("\t");
- String strContactName = aParts[0];
- String strContactAddress = aParts[1];
- strProcessingResult+=
- String.format(
- "Name: %s ; Address: %s\n",
- strContactName,
- strContactAddress
- );
- }//for
- return strProcessingResult;
- }//processRawData
- public static final String SOURCE_HTTPS =
- "https://arturmarques.com/edu/contacts.TSV";
- public static final String SOURCE_HTTP =
- "http://arturmarques.com/edu/contacts.TSV";
- Context mContext;
- TextView mTvRemoteContent;
- MyAsyncTask mAsyncTaskThatReadsTheRemoteContent;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- init();
- }//onCreate
- void approach1(){
- /*
- we can NOT consume external resources
- in the same thread that handles the user interface!
- There is the risk that these resources take too long
- to become available: during that time the user interface
- would be unresponsive (A.N.R.), which is not acceptable.
- We must do it in a different thread
- We must do it asynchronously
- */
- //E/@AmHttp: android.os.NetworkOnMainThreadException
- mTvRemoteContent.setText(
- AmHttp.consumeHttpsAtUrl(
- SOURCE_HTTPS
- )
- );
- }//approach1
- /*
- will consume in its own thread
- will consume asynchronously
- */
- void approach2(){
- /*
- use MyAsyncTask via mAsyncTaskThatReadsTheRemoteContent
- */
- mAsyncTaskThatReadsTheRemoteContent.execute(
- SOURCE_HTTPS
- );
- }//approach2
- void init(){
- mContext = this;
- mTvRemoteContent = findViewById(R.id.idTvRemoteContent);
- mAsyncTaskThatReadsTheRemoteContent =
- new MyAsyncTask();
- //approach1(); //FAIL!
- approach2(); //OK!
- }//init
- }
- //**
- package com.joythis.android.minimalhttps;
- import android.util.Log;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.nio.charset.StandardCharsets;
- import javax.net.ssl.HttpsURLConnection;
- public class AmHttp {
- public final static String TAG = "@AmHttp";
- public static final int END_OF_CONTENT = -1;
- public static String consumeHttpsAtUrl(
- String pUrl
- ){
- String strRemoteContent = "";
- try{
- URL url = new URL(pUrl);
- HttpsURLConnection httpsCon =
- (HttpsURLConnection)
- url.openConnection();
- if(httpsCon!=null){
- InputStream is =
- httpsCon.getInputStream();
- //assures the correct consumption of UTF8 symbols in the stream
- InputStreamReader isr =
- new InputStreamReader(
- is,
- StandardCharsets.UTF_8
- );
- char c; int iByte;
- while((iByte=isr.read())!=END_OF_CONTENT){
- c = (char)iByte;
- strRemoteContent += c;
- }//while
- isr.close();
- is.close();
- return strRemoteContent;
- }
- }//try
- catch (Exception e){
- String strMsg = e.toString();
- Log.e(
- TAG//stamp
- ,
- strMsg
- );
- }//catch
- return strRemoteContent;
- }//consumeHttpsAtUrl
- public static String consumeHttpAtUrl(
- String pUrl
- ){
- String strRemoteContent = "";
- try{
- URL url = new URL(pUrl);
- HttpURLConnection httpCon =
- (HttpURLConnection)
- url.openConnection();
- if(httpCon!=null){
- InputStream is = httpCon.getInputStream();
- //assures the correct consumption of UTF8 symbols in the stream
- InputStreamReader isr =
- new InputStreamReader(
- is,
- StandardCharsets.UTF_8
- );
- char c; int iByte;
- while((iByte=isr.read())!=END_OF_CONTENT){
- c = (char)iByte;
- strRemoteContent += c;
- }//while
- isr.close();
- is.close();
- return strRemoteContent;
- }//if
- }//try
- catch (Exception e){
- String strMsg = e.toString();
- Log.e(
- TAG//stamp
- ,
- strMsg
- );
- }//catch
- return strRemoteContent;
- }//consumeHttpAtUrl
- }//AmHttp
- //**
- <?xml version="1.0" encoding="utf-8"?>
- <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:app="http://schemas.android.com/apk/res-auto"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- tools:context=".MainActivity">
- <TextView
- android:id="@+id/idTvRemoteContent"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Hello World!"
- app:layout_constraintBottom_toBottomOf="parent"
- app:layout_constraintLeft_toLeftOf="parent"
- app:layout_constraintRight_toRightOf="parent"
- app:layout_constraintTop_toTopOf="parent" />
- </androidx.constraintlayout.widget.ConstraintLayout>
- //**
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.joythis.android.minimalhttps">
- <!-- non-dangerous permission -->
- <uses-permission android:name="android.permission.INTERNET"></uses-permission>
- <application
- android:allowBackup="true"
- android:icon="@mipmap/ic_launcher"
- android:label="@string/app_name"
- android:roundIcon="@mipmap/ic_launcher_round"
- android:supportsRtl="true"
- android:theme="@style/Theme.MinimalHTTPS">
- <activity android:name=".MainActivity">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- </application>
- </manifest>
Advertisement
Add Comment
Please, Sign In to add comment