Как мне войти на сайт, используя мой пользовательский вид в Android Studio - PullRequest
0 голосов
/ 17 февраля 2019

Я пытаюсь зайти на этот сайт https://www.ethiosouthwest.com, используя свой собственный дизайн, чтобы избежать просмотра веб-страниц, поскольку он имеет худший дизайн, а также не адаптивный веб-сайт.После успешного входа в систему он должен перенаправить меня на эту ссылку https://www.ethiosouthwest.com/mainpage.php, и я буду использовать jsoup для получения данных.Но кажется невозможным, может ли какое-нибудь тело помочь мне, я вроде застрял.

Я пробовал это, но это не похоже на работу.

@file:Suppress("DEPRECATION")

package pino.com.studentportal

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.app.ProgressDialog
import android.content.Context
import android.content.DialogInterface
import android.net.ConnectivityManager
import android.os.AsyncTask
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.*
import java.io.*
import java.net.HttpURLConnection
import java.net.MalformedURLException
import java.net.URL

class LoginActivity : AppCompatActivity() {
    //Initializing all the variables
    lateinit var userName: EditText
    lateinit var passWord: EditText
    lateinit var dataUser: StringBuffer
    lateinit var loginBtn: Button
    lateinit var schoolname: Spinner
    lateinit var schoolYear: Spinner
    lateinit var errorResult: TextView
    lateinit var schoolY: String
    lateinit var schoolN: String

    override fun onCreate(savedInstanceState: Bundle?) {
        //Executed when app opened at first
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        userName = findViewById(R.id.alphaname)
        passWord = findViewById(R.id.alphapassword)
        loginBtn = findViewById(R.id.loginbtn)
        schoolname = findViewById(R.id.alphaschool)
        schoolYear = findViewById(R.id.alphayear)
        errorResult = findViewById(R.id.alphapassword)

        //Alert Dialog For Errors
        val errorDialog = AlertDialog.Builder(this)

       //School Branches in an Array format

       val schoolNames = arrayOf("Main Campus(Lafto)","Lafto 1-4 Division","Lafto KG Division","Jemo 1-4 Division","Jemo 5-12 Division","Jemo KG Division")

        //The Date of the required report

        val schoolYears = arrayOf("2007","2008","2009","2010","2011")

        //Set the spinner data to the array above (schoolNames)

        schoolname.adapter = ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,schoolNames)
        schoolname.onItemSelectedListener = object: AdapterView.OnItemSelectedListener{
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {

                //Set the selected Item to the string variable

                schoolN = schoolNames[position]
        }

            override fun onNothingSelected(parent: AdapterView<*>?) {
                //Set it to empty string if none is selected
                //Create AlertDialog if none is selected

                errorDialog.setTitle("Error")
                errorDialog.setMessage("Please select the Campus")
                errorDialog.setNeutralButton("OK", DialogInterface.OnClickListener { dialog, which ->
            })
                errorDialog.show()

        }
    }

        //Set the spinner data to the array above (schoolYears)

        schoolYear.adapter = ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,schoolYears)
        schoolYear.onItemSelectedListener = object: AdapterView.OnItemSelectedListener{
            override fun onNothingSelected(parent: AdapterView<*>?) {
                //Set the string variable to empty string
                //Create AlertDialog if none is selected
                errorDialog.setTitle("Error")
            errorDialog.setMessage("Please select the Year")
            errorDialog.setNeutralButton("OK", DialogInterface.OnClickListener { dialog, which ->
            })
            errorDialog.show()
        }

        override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
            //Set it to the item in the array which is selected

            schoolY = schoolYears[position]
        }
    }
    loginBtn.setOnClickListener {
        //When "Login" Button is clicked execute the AsyncTask process
        LoginBackground().execute()
    }

}

@SuppressLint("StaticFieldLeak")
internal inner class LoginBackground : AsyncTask<Void, Void, String>() {
    //Initialize progressDialog for later

    lateinit var progressDialog : ProgressDialog

    //To check If internet is accessible

    var hasInternet = false

    //Before Executing the LoginBackground completing the data
    override fun onPreExecute() {

        dataUser.insert(1,"alphaschool=&alphausername=&alphapassword=&alphayear=")
        dataUser.insert(12,schoolN)
        dataUser.insert(27,userName.toString())
        dataUser.insert(42,passWord.toString())
        dataUser.insert(53,schoolY)
        val context = this@LoginActivity
        progressDialog = ProgressDialog(context)
        progressDialog.setMessage("Authenticating User...")
        progressDialog.setCancelable(false)
        progressDialog.show()
    }
    override fun doInBackground(vararg params: Void?): String {
        //Check if internet is available and Post the request to the website's form
        return if(isNetworkAvailable()){
            hasInternet = true

            //Url for the website to post it to

            val url = "http://www.ethiosouthwest.com/index.php#slidepanel"

            //Defined method to post the request and save cookies

            postRequest(url,dataUser.toString(),10000)

        }else{
            //If there is no connection
            //Show AlertDialog for no connection
            return ""
        }
    }
    //After Background task completed execute this method
    override fun onPostExecute(result: String?) {
        super.onPostExecute(result)
        //Alert Dialog for error
        val errorDialog = AlertDialog.Builder(this@LoginActivity)
        progressDialog.dismiss()
        if(hasInternet == false){

            //Error Dialog for error in connection

            errorDialog.setTitle("Error Internet")
            errorDialog.setMessage("Connection Error")
            errorDialog.setNeutralButton("OK", DialogInterface.OnClickListener { dialog, which ->  })
            errorDialog.show()
        }
    }

}
//private function to check the network / Data usage is accessible
private fun isNetworkAvailable(): Boolean{
    val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    val activeNetworkInfo = connectivityManager.activeNetworkInfo
    return activeNetworkInfo != null && activeNetworkInfo.isConnected
}

//Private function to post the data of the user
private fun postRequest(url:String, post_data:String, len:Int):String {
    val address = URL(url)
    //AlertDialog for errors
    val errorDialog = AlertDialog.Builder(this)

    val data = StringBuffer()
    var conn: HttpURLConnection?
    try
    {
        conn = address.openConnection() as HttpURLConnection
    }
    catch (e: IOException) {
        //Create AlertDialog for this error
        errorDialog.setTitle("Error")
        errorDialog.setMessage("Open connection error")
        errorDialog.setNeutralButton("OK", DialogInterface.OnClickListener { dialog, which ->  })
        errorDialog.show()
        return "Open connection error"
    }
    conn.setRequestProperty("Connection", "keep-alive")
    conn.setRequestProperty("Accept-Language", "en;q=0.6")
    conn.setRequestProperty("Accept-Charset", "utf-8")
    conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
    conn.setRequestProperty("Cookie", "")
    conn.doOutput = true
    conn.doInput = true
    //conn.setInstanceFollowRedirects(true);
    setCookie(conn)
    //POST data:
    data.append(post_data)
    try
    {
        conn.connect()
    }
    catch (e:IOException) {
        //Create AlertDialog for this error
        errorDialog.setTitle("Error")
        errorDialog.setMessage("Connecting error")
        errorDialog.setNeutralButton("OK", DialogInterface.OnClickListener { dialog, which ->  })
        errorDialog.show()
        return "Connecting error"
    }
    val dataOS: DataOutputStream?
    try
    {
        dataOS = DataOutputStream(conn.getOutputStream())
    }
    catch (e2:IOException) {
        //Create AlertDialog for this error
        errorDialog.setTitle("Error")
        errorDialog.setMessage("Out stream error")
        errorDialog.setNeutralButton("OK", DialogInterface.OnClickListener { dialog, which ->  })
        errorDialog.show()
        return "Out stream error"
    }
    try
    {
        dataOS.writeBytes(data.toString())
    }
    catch (e:IOException) {
        //Create AlertDialog for this error
        errorDialog.setTitle("Error")
        errorDialog.setMessage("Out stream error 1")
        errorDialog.setNeutralButton("OK", DialogInterface.OnClickListener { dialog, which ->  })
        errorDialog.show()
        return "Out stream error 1"
    }
    /*If redirect: */
    val status:Int
    try
    {
        status = conn.responseCode
    }
    catch (e2:IOException) {
        //Create AlertDialog for this error
        errorDialog.setTitle("Error")
        errorDialog.setMessage("Response error")
        errorDialog.setNeutralButton("OK", DialogInterface.OnClickListener { dialog, which ->  })
        errorDialog.show()
        return "Response error"
    }

    if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER)
    {
        val new_url = conn.getHeaderField("Location")
        val cookies = conn.getHeaderField("Set-Cookie")
        val red_url:URL
        try
        {
            red_url = URL(new_url)
        }
        catch (e:MalformedURLException) {
            //Create AlertDialog for this error
            errorDialog.setTitle("Error")
            errorDialog.setMessage("Redirect error")
            errorDialog.setNeutralButton("OK", DialogInterface.OnClickListener { dialog, which ->  })
            errorDialog.show()
            return "Redirect error"
        }
        try
        {
            conn = red_url.openConnection() as HttpURLConnection
        }
        catch (e:IOException) {
            //Create AlertDialog for this error
            errorDialog.setTitle("Error")
            errorDialog.setMessage("Redirect connection error")
            errorDialog.setNeutralButton("OK", DialogInterface.OnClickListener { dialog, which ->  })
            errorDialog.show()
            return "Redirect connection error"
        }
        //conn.setRequestProperty("Content-type", "text/html");
        conn.setRequestProperty("Connection", "keep-alive")
        conn.setRequestProperty("Accept-Language", "ru,en-GB;q=0.8,en;q=0.6")
        conn.setRequestProperty("Accept-Charset", "utf-8")
        conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
        conn.setRequestProperty("Cookie", cookies)
        conn.doOutput = true
        conn.doInput = true
        //conn.setInstanceFollowRedirects(true);
    }
    val `in`: InputStream?
    try
    {
        `in` = conn.inputStream as java.io.InputStream
    }
    catch (e:IOException) {
        //Create AlertDialog for this error
        errorDialog.setTitle("Error")
        errorDialog.setMessage("In stream error")
        errorDialog.setNeutralButton("OK", DialogInterface.OnClickListener { dialog, which ->  })
        errorDialog.show()
        return "In stream error"
    }
    val reader: InputStreamReader?
    try
    {
        reader = InputStreamReader(`in`, "UTF-8")
    }
    catch (e: UnsupportedEncodingException) {
        //Create AlertDialog for this error
        errorDialog.setTitle("Error")
        errorDialog.setMessage("In stream error")
        errorDialog.setNeutralButton("OK", DialogInterface.OnClickListener { dialog, which ->  })
        errorDialog.show()
        return "In stream error"
    }
    val buf = CharArray(len)
    try
    {
        reader.read(buf)
    }
    catch (e:IOException) {
        //Create AlertDialog for this error
        errorDialog.setTitle("Error")
        errorDialog.setMessage("In stream error")
        errorDialog.setNeutralButton("OK", DialogInterface.OnClickListener { dialog, which ->  })
        errorDialog.show()
        return "In stream error"
    }
    get_cookie(conn)
    return (String(buf))
}
fun get_cookie(conn:HttpURLConnection) {
    val shPreferences = getSharedPreferences("cookies", Context.MODE_PRIVATE)
    val cookNew:String
    val cookiesHeader:String
    if (conn.getHeaderField("Set-Cookie") != null)
    {
        cookiesHeader = "Set-Cookie"
    }
    else
    {
        cookiesHeader = "Cookie"
    }
    cookNew = conn.getHeaderField(cookiesHeader)
    if (cookNew.indexOf("sid", 0) >= 0)
    {
        val editor = shPreferences.edit()
        editor.putString("Cookie", cookNew)
        editor.apply()
    }
}
fun setCookie(conn:HttpURLConnection) {
    val shPreferences = getSharedPreferences("cookies", Context.MODE_PRIVATE)
    val cookiesHeader = "Cookie"
    val cook = shPreferences.getString(cookiesHeader, "no_cookie")
    if (cook != "no_cookie")
    {
        conn.setRequestProperty(cookiesHeader, cook)
    }
}

}

...