-
PHP와 Android 연동하기Web/PHP 2020. 10. 13. 13:59SMALL
Centos7에 PHP 설치하기
2020/09/29 - [Web/Nginx] - Nginx에 php-fpm 설치하기 for Centos7
Centos7에 MySQL 설치하기
2020/10/06 - [Web/Nginx] - Nginx에 MySQL 설치하기 for Centos7
안드로이드 앱에서 서버로 접근하기 위해서는 보안상 앱이 직접 전송하는 것은 불가능하고
둘의 중간을 연결해주는 서버사이드 언어가 필요하다.
서버가 앱이 사용할 mysql 계정과 사용권한을 설정한 후
서버의 특정 파일을 이용해 DB에 데이터를 읽고 쓰고 수정할 수 있게 된다. (권한이 허용하는 안에서)
앱과 서버를 연결해주는 서버사이드 언어로는 PHP가 많이 사용된다.
PHP를 이용해 Android와 서버를 연동하는 방법을 알아보자.
MySQL 세팅하기
1. 먼저 mysql 계정 로그인 후 데이터베이스 및 테이블을 생성
mysql> CREATE DATABASE androidApp; Query OK, 1 row affected (0.00 sec) mysql> CREATE TABLE users ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, userID VARCHAR(30) NOT NULL, password VARCHAR(30) NOT NULL, username VARCHAR(30) NOT NULL )
2. 안드로이드 앱에서 서버로 접근할 계정을 생성한 뒤, 권한을 부여
mysql> CREATE USER 'userID'@'%' IDENTIFIED BY 'password'; Query OK, rows affected (0.00 sec) mysql> GRANT ALL ON androidApp.* TO userID'%' IDENTIFIED BY 'password'; Query OK, rows affected (0.00 sec) mysql> FLUSH PRIVILEGES; Query OK, rows affected (0.00 sec)
3. 서버의 방화벽을 해제
$ firewall-cmd --zone=public --add-service=mysql --permanent $ firewall-cmd --reload
서버 PHP 파일 세팅하기
1. mysql에 접속할 php 파일 구성을 살펴보기
<?php $con = mysqli_connect('IP', 'userID', 'password'); if(mysqli_query($con, $sql) { echo "Connected"; } mysqli_close($con); ?>
mysqli_connect 함수를 이용해 접속할 서버의 주소, mysql에 생성한 ID와 비밀번호를 인자값으로 주면 접속할 수 있다.
connect 이후 마지막에 mysqli_close로 종료시켜줘야 한다.
2. PHP로 DB에 POST로 insert 하는 파일 만들기
<?php $con = mysqli_connect('IP', 'userID', 'password'); if(mysqli_connect_error($con){ echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $userID = $_POST['userID']; $password = $_POST['password']; $query = "INSERT INTO users VALUES('$userID', '$password')"; $result = mysqli_query($con, $query); if($result) echo "INSERT success"; else echo "INSERT fail"; mysqli_close($con); ?>
GET은 $_POST 이 부분을 $_GET 으로만 수정하면 된다.
java 파일 수정하기
MySQL에 접속할 때는 GET 과 POST 로 접속할 수 있다.
1. 먼저 AndroidMainfest 파일에 인터넷 사용 퍼미션을 허가
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
2. GET 매서드는 HttpGet, HttpClient 두 가지 클래스를 이용한다.
URL url = new URL(link); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(); request.setURI(new URI(link));
3. 두 가지 클래스를 생성한 뒤 execute 해준다.
HttpResponse response = client.execute(request); BufferedReader in = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
4. POST 매서드는 URLEncoder, URLConnection 두 가지 클래스를 이용한다.
URL url = new URL(link); String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8"); data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8"); URLConnection conn = url.openConnection();
4. class 생성 후 response를 받을 stream을 열어준다.
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write( data ); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
아이디 패스워드 조회 예시
PHP SELECT 파일
<?php $con=mysqli_connect("mysql10.000webhost.com","username","password","db_name"); if (mysqli_connect_errno($con)) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $username = $_POST['username']; $password = $_POST['password']; $result = mysqli_query($con,"SELECT Role FROM table1 where Username='$username' and Password='$password'"); $row = mysqli_fetch_array($result); $data = $row[0]; if($data){ echo $data; } mysqli_close($con); ?>
src/com.example.phpmysql/MainActivity.java
package com.example.phpmysql; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends Activity { private EditText usernameField,passwordField; private TextView status,role,method; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); usernameField = (EditText)findViewById(R.id.editText1); passwordField = (EditText)findViewById(R.id.editText2); status = (TextView)findViewById(R.id.textView6); role = (TextView)findViewById(R.id.textView7); method = (TextView)findViewById(R.id.textView9); } public void login(View view){ String username = usernameField.getText().toString(); String password = passwordField.getText().toString(); method.setText("Get Method"); new SigninActivity(this,status,role,0).execute(username,password); } public void loginPost(View view){ String username = usernameField.getText().toString(); String password = passwordField.getText().toString(); method.setText("Post Method"); new SigninActivity(this,status,role,1).execute(username,password); } }
src/com.example.phpmysql/SigninActivity.java
package com.example.phpmysql; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.URI; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.content.Context; import android.os.AsyncTask; import android.widget.TextView; public class SigninActivity extends AsyncTask{ private TextView statusField,roleField; private Context context; private int byGetOrPost = 0; //flag 0 means get and 1 means post.(By default it is get.) public SigninActivity(Context context,TextView statusField,TextView roleField,int flag) { this.context = context; this.statusField = statusField; this.roleField = roleField; byGetOrPost = flag; } protected void onPreExecute(){ } @Override protected String doInBackground(String... arg0) { if(byGetOrPost == 0){ //means by Get Method try{ String username = (String)arg0[0]; String password = (String)arg0[1]; String link = "http://myphpmysqlweb.hostei.com/login.php?username="+username+"& password="+password; URL url = new URL(link); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(); request.setURI(new URI(link)); HttpResponse response = client.execute(request); BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line=""; while ((line = in.readLine()) != null) { sb.append(line); break; } in.close(); return sb.toString(); } catch(Exception e){ return new String("Exception: " + e.getMessage()); } } else{ try{ String username = (String)arg0[0]; String password = (String)arg0[1]; String link="http://myphpmysqlweb.hostei.com/loginpost.php"; String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8"); data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8"); URL url = new URL(link); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write( data ); wr.flush(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line = null; // Read Server Response while((line = reader.readLine()) != null) { sb.append(line); break; } return sb.toString(); } catch(Exception e){ return new String("Exception: " + e.getMessage()); } } } @Override protected void onPostExecute(String result){ this.statusField.setText("Login Successful"); this.roleField.setText(result); } }
build.gradle
android { useLibrary 'org.apache.http.legacy' }
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <EditText android:id="@+id/editText2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@+id/editText1" android:layout_below="@+id/editText1" android:layout_marginTop="25dp" android:ems="10" android:inputType="textPassword" > </EditText> <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_marginTop="44dp" android:ems="10" > <requestFocus android:layout_width="wrap_content" /> </EditText> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/editText1" android:layout_alignParentLeft="true" android:text="@string/Username" /> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:text="@string/App" android:textAppearance="?android:attr/textAppearanceLarge" /> <TextView android:id="@+id/textView7" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/textView5" android:layout_alignLeft="@+id/textView6" android:text="@string/Role" android:textAppearance="?android:attr/textAppearanceMedium" android:textSize="10sp" /> <TextView android:id="@+id/textView5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textView6" android:layout_marginTop="27dp" android:layout_toLeftOf="@+id/editText1" android:text="@string/LoginRole" /> <TextView android:id="@+id/textView8" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/textView6" android:layout_alignLeft="@+id/textView5" android:layout_marginBottom="27dp" android:text="@string/method" /> <TextView android:id="@+id/textView4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView8" android:layout_below="@+id/button1" android:layout_marginTop="86dp" android:text="@string/LoginStatus" /> <TextView android:id="@+id/textView6" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/textView4" android:layout_centerHorizontal="true" android:text="@string/Status" android:textAppearance="?android:attr/textAppearanceMedium" android:textSize="10sp" /> <TextView android:id="@+id/textView9" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/textView8" android:layout_alignLeft="@+id/textView6" android:text="@string/Choose" android:textAppearance="?android:attr/textAppearanceMedium" android:textSize="10sp" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_toRightOf="@+id/textView6" android:onClick="loginPost" android:text="@string/LoginPost" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/button2" android:layout_alignBottom="@+id/button2" android:layout_alignLeft="@+id/textView2" android:onClick="login" android:text="@string/LoginGet" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/editText2" android:layout_alignBottom="@+id/editText2" android:layout_alignParentLeft="true" android:text="@string/Password" /> </RelativeLayout>
Strings.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">PHPMYSQL</string> <string name="action_settings">Settings</string> <string name="hello_world">Hello world!</string> <string name="Username">Username</string> <string name="Password">Password</string> <string name="LoginGet">Login - Get</string> <string name="LoginPost">Login - Post</string> <string name="App">Login Application</string> <string name="LoginStatus">Login Status</string> <string name="LoginRole">Login Role</string> <string name="Status">Not login</string> <string name="Role">Not assigned</string> <string name="method">Login Method</string> <string name="Choose">Choose Method</string> </resources>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.phpmysql" > <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.phpmysql.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
[참고문헌]
1. www.tutorialspoint.com/android/android_php_mysql.htm
LIST'Web > PHP' 카테고리의 다른 글
댓글