使用Curl制作Android登录表单。

huangapple go评论89阅读模式
英文:

Make android login form using Curl

问题

I can certainly help you analyze the code and provide suggestions to resolve the issues you're facing. However, since you've requested only the translated version without additional content, here's the translated version of your provided text:

I need help to make login using Curl, I just tried to make it but it always failed. Do I need a PHP file or not? If yes, can you give me an example of how to use it?

Here is my URL to attempt login using "nik_baru" and password:

[http://hrd.tvip.co.id/rest_server/api/login/index][1]

And here is my code:
[...]
(package and imports are not translated)
[...]

And this is the XML code:
[...]
(XML layout code is not translated)
[...]

Can you assist in solving this issue?

[1]: http://hrd.tvip.co.id/rest_server/api/login/index

If you need any assistance with the provided code or have questions about it, please let me know.

英文:

I need help to make login using Curl, I just tried make it but it always failed. do I need php file or no ? if yes, can you give me an example how to use it.

here is my url to make login using nik_baru and password

http://hrd.tvip.co.id/rest_server/api/login/index

And here is my code

package com.example.eis2;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    EditText editTextnik_baru;
    EditText editTextpassword;
    Button buttonlogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editTextnik_baru = (EditText) findViewById(R.id.editTextnik_baru);
        editTextpassword = (EditText) findViewById(R.id.editTextpassword);
        buttonlogin = (Button) findViewById(R.id.buttonlogin);

        buttonlogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(!editTextnik_baru.getText().equals("")){
                    sendLogin();

                } else {
                    editTextnik_baru.setError("Please insert NIK");
                    editTextpassword.setError("Please insert password");
                }
            }
        });
    }
    private void sendLogin() {
        String url = "http://hrd.tvip.co.id/rest_server/api/login/index";
        url += editTextnik_baru.getText();
        final String nik_baru = editTextnik_baru.getText().toString().trim();

        StringRequest loginRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONArray array = new JSONArray("data");
                            JSONObject json = array.getJSONObject(0);
                            String status = json.getString("nik_baru");
                            System.out.println("data "+ status);
//                            JSONObject json = getJSONObject("data");
                            if(status.equals(nik_baru)){
                                Log.d("tvip", "success");
                                Intent intent = new Intent(MainActivity.this, menu.class);
                                startActivity(intent);
                                finish();
                            }else{
                                Toast.makeText(getApplicationContext(), "Username & Password Salah", Toast.LENGTH_LONG).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(),"Error", Toast.LENGTH_LONG).show();
                    }
                }
        ){
            @Override
            protected Map<String, String> getParams(){
                HashMap<String, String> params = new HashMap<>();
                params.put("nik_baru", editTextnik_baru.getText().toString());
                params.put("password", editTextpassword.getText().toString());
                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(loginRequest);
    }
}

and this is it's xml code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:background="#00d0ff"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/logoeis"
        android:layout_width="148dp"
        android:layout_height="140dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="90dp"
        app:srcCompat="@drawable/logoeis" />
    <ImageView
        android:id="@+id/logoasa"
        android:layout_width="38dp"
        android:layout_height="43dp"
        android:layout_below="@+id/logoeis"
        android:layout_marginLeft="300dp"
        android:layout_marginTop="-200dp"
        app:srcCompat="@drawable/logoasa" />
    <ImageView
        android:id="@+id/logotvip"
        android:layout_width="38dp"
        android:layout_height="43dp"
        android:layout_below="@+id/logoeis"
        android:layout_marginLeft="250dp"
        android:layout_marginTop="-200dp"
        app:srcCompat="@drawable/logotvip" />
    <EditText
        android:id="@+id/editTextnik_baru"
        android:layout_width="241dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:layout_below="@+id/logoeis"
        android:layout_centerHorizontal="true"
        android:hint="NIK Baru"
        android:inputType="text"
        android:textColor="#000000"
        android:selectAllOnFocus="true"/>
    <EditText
        android:id="@+id/editTextpassword"
        android:layout_width="241dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editTextnik_baru"
        android:layout_centerHorizontal="true"
        android:hint="Password"
        android:textColor="#000000"
        android:inputType="textPassword"
        android:selectAllOnFocus="true"/>
    <Button
        android:id="@+id/buttonlogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editTextpassword"
        android:layout_centerHorizontal="true"
        android:text="Login"
        android:layout_marginTop="15dp" />
    <TextView
        android:id="@+id/eis"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Employee Information System"
        android:textSize="23dp"
        android:layout_marginTop="12dp"
        android:textColor="#000000"
        android:layout_below="@+id/buttonlogin"
        android:layout_centerHorizontal="true"/>
    <TextView
        android:id="@+id/version"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Version 1.0"
        android:textSize="23dp"
        android:layout_marginTop="12dp"
        android:textColor="#000000"
        android:layout_below="@+id/eis"
        android:layout_centerHorizontal="true"/>
</RelativeLayout>

Can you guys solve this problem ?

答案1

得分: 0

这只是一个示例... 您特定登录系统的确切编码可能会有所不同。

服务器登录文件 PHP 类似于以下内容:

if (isset($_POST['username']) && $_POST['username'] != '') {
    $loginPassword = $_POST['password'];
    $username = $_POST['username'];
    $sql = "SELECT `id`, `username`, `email`, `password`, `key` FROM `TABLE_NAME` WHERE `username`=:username";
    $LoginRS_query = $conn->prepare($sql);
    $LoginRS_query->bindValue(':username', $username, PDO::PARAM_STR);
    $LoginRS_query->execute();
    $LoginRS = $LoginRS_query->fetch(PDO::FETCH_ASSOC);
    $totalRows = $LoginRS_query->rowCount();

    if($totalRows > 0) {
        $db_key = $LoginRS['key'];
        $peppered = hash_hmac("sha256", $loginPassword, $db_key);
        $db_pwd = $LoginRS['password'];
        if(password_verify($peppered, $db_pwd)) {
            $loginFoundUser = 'true';
        } else {
            $loginFoundUser = 'false';
        }
    }

    if($loginFoundUser == 'true') {
        $loginID =  $LoginRS['id'];
        $loginUserName = $LoginRS['username'];

        $LoginRS_query->closeCursor();

        echo "success";

        $response = array('id' => $loginID, 'username' => $loginUserName);
        echo json_encode($response);
    } else {
        $LoginRS_query->closeCursor();
        echo "no user found";
    }
} else {
    echo "access failed";
}

然后在您的活动文件的 sendLogin() 中...

public void onResponse(String response) {
    if (response.contains("success")) {
        String res = response.substring(response.indexOf("{"));
        try {
            JSONObject jsonObject = new JSONObject(res);
            final String loginID = jsonObject.getString("id");
            final String loginUser = jsonObject.getString("username");

            Intent intent = new Intent(MainActivity.this, menu.class);
            intent.putExtra("id", loginID); // 添加了此行
            intent.putExtra("username", loginUser); // 添加了此行
            startActivity(intent);
            finish();
        } catch (JSONException e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "Login Error " + e, Toast.LENGTH_LONG).show();
        }
    } else {
        Toast.makeText(getApplicationContext(), "Username & Password Salah", Toast.LENGTH_LONG).show();
    }
}

仅在您需要在其他任务中使用用户名或 ID 时才需要使用 intent.putExtra

英文:

This is just an example... the <b>exact</b> coding for your particular login system may be different.

The server login file PHP would be similar to this:

if (isset($_POST[&#39;username&#39;]) &amp;&amp; $_POST[&#39;username&#39;] != &#39;&#39;) {
	$loginPassword = $_POST[&#39;password&#39;];
	$username = $_POST[&#39;username&#39;];
	$sql = &quot;SELECT `id`, `username`, `email`, `password`, `key` FROM `TABLE_NAME` WHERE `username`=:username&quot;;
	$LoginRS_query = $conn-&gt;prepare($sql);
	$LoginRS_query-&gt;bindValue(&#39;:username&#39;, $username, PDO::PARAM_STR);
	$LoginRS_query-&gt;execute();
	$LoginRS = $LoginRS_query-&gt;fetch(PDO::FETCH_ASSOC);
	$totalRows = $LoginRS_query-&gt;rowCount();
	
	if($totalRows &gt; 0) {
		$db_key = $LoginRS[&#39;key&#39;];
		$peppered = hash_hmac(&quot;sha256&quot;, $loginPassword, $db_key);
		$db_pwd = $LoginRS[&#39;password&#39;];
		if(password_verify($peppered, $db_pwd)) {
			$loginFoundUser = &#39;true&#39;;
		} else {
			$loginFoundUser = &#39;false&#39;;
		}
	}
	
	if($loginFoundUser == &#39;true&#39;) {
		$loginID =  $LoginRS[&#39;id&#39;];
		$loginUserName = $LoginRS[&#39;username&#39;];
		
		$LoginRS_query-&gt;closeCursor();
		
		echo &quot;success&quot;;
		
		$response = array(&#39;id&#39; =&gt; $loginID, &#39;username&#39; =&gt; $loginUserName);
    	echo json_encode($response);
	} else {
		$LoginRS_query-&gt;closeCursor();
		echo &quot;no user found&quot;;
	}
} else {
	echo &quot;access failed&quot;;
}

Then in your activity file inside sendLogin() ...

public void onResponse(String response) {
    if (response.contains(&quot;success&quot;)) {
        String res = response.substring(response.indexOf(&quot;{&quot;));
        try {
            JSONObject jsonObject = new JSONObject(res);
	        final String loginID = jsonObject.getString(&quot;id&quot;);
            final String loginUser = jsonObject.getString(&quot;username&quot;);
            
	        Intent intent = new Intent(MainActivity.this, menu.class);
			intent.putExtra(&quot;id&quot;, loginID); // added this line
    		intent.putExtra(&quot;username&quot;, loginUser); // added this line
	    	startActivity(intent);
		    finish();
        } catch (JSONException e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), &quot;Login Error &quot; + e, Toast.LENGTH_LONG).show();
        }
	}else{
    	Toast.makeText(getApplicationContext(), &quot;Username &amp; Password Salah&quot;, Toast.LENGTH_LONG).show();
    }

The intent.putExtra is only needed if you will need your username or ID elsewhere to perform other tasks

huangapple
  • 本文由 发表于 2020年8月21日 11:27:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/63516091.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定