코딩하는 해달이

[Android Studio] OKHTTP3와 flask를 이용해 DB에 데이터 전송하기 1 본문

개인 공부/Android Studio

[Android Studio] OKHTTP3와 flask를 이용해 DB에 데이터 전송하기 1

코딩하는 해달 2022. 9. 7. 12:42

Version & 참고 링크

더보기

Version

 -운영체제 : Window 10

 -PYTHON : python 3.10.6 64-bit

 -Visual Studio Code : Visual Studio Code 1.70.1(user setup)

 -Android Studio : android-studio-2021.2.1.15-windows

 -MySQL : 8.0.29

 

이 글은 아래의 링크를 바탕으로 작성한 글입니다.

(제가 이해한 대로 글을 쓴 것이므로 틀린 내용이 있을 수도 있습니다.)

https://joyfulbean.tistory.com/114

 

https://square.github.io/okhttp/

 

https://velog.io/@jinny_0422/Android-Okhttp3-%EC%82%AC%EC%9A%A9%ED%95%98%EC%97%AC-%EB%84%A4%ED%8A%B8%EC%9B%8C%ED%81%AC-%ED%86%B5%EC%8B%A0-%ED%95%98%EA%B8%B0

 

https://stickode.tistory.com/41

 

https://hgusight.github.io/study/app/android/

 

https://gun0912.tistory.com/80 // 안드로이드 스튜디오 에러 해결 "CLEARTEXT communication to XXXX not permitted by network security policy"

 

https://ninano1109.tistory.com/135

 

https://stackoverflow.com/questions/47957433/sql-typeerror-cant-concat-tuple-to-bytes // flask sql문 에러

"can't concat tuple to bytes"

 

https://stackoverflow.com/questions/19238781/python-mysql-typeerror-execute-takes-from-2-to-4-positional-arguments-but-5-w  // flask sql문 에러

"Cursor.execute() takes from 2 to 3 positional arguments but 5 were given"

 

https://www.stechstar.com/user/zbxe/AlgorithmPython/75092

 

지난 포스팅에선 MySQL내의 데이터를 http로 전송하는 방법에 대해 포스팅을 했습니다.

파이썬 - Flask를 이용해서 JSON인코딩한 MySql 데이터를 Android Studio에 보내기 (1)

이번엔 반대로 안드로이드 스튜디오에서 http에 요청해 MySQL에 데이터를 전송해보겠습니다.

(물론 데이터 흐름도 이전과 반대로 흘러갑니다.)

 

가장 먼저 웹서버를 사용하기때문에 인터넷 접속 권한을 지정해야합니다.App > manifests > AndroidManifest.xml 파일로 들어가서 아래 코드를 추가해줍니다.

<uses-permission android:name="android.permission.INTERNET" /> <-- <manifest> 태그 안에 추가 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>  // <--<manifest> 태그 안에 추가 -->

<-- <application> 태그 안에 추가 -->
android:usesCleartextTraffic="true"

그리고 OKHTTP3를 사용하기때문에 gradle도 변경해주어야합니다.

간단히 아이디 비밀번호 이름을 DB에 넣어보겠습니다.

 

우선 데이터를 전송할 폼을 만들어봅시다. activity_main.xml 코드입니다.

<?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/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:text="join"
        android:textSize="40sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />


    <EditText
        android:id="@+id/input_pwd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="50dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="50dp"
        android:autofillHints=""
        android:ems="10"
        android:hint="password"
        android:inputType="textPassword"
        android:minHeight="48dp"
        android:textColorHint="#757575"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/input_id" />

    <EditText
        android:id="@+id/input_id"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="50dp"
        android:layout_marginTop="32dp"
        android:layout_marginEnd="50dp"
        android:autofillHints=""
        android:ems="10"
        android:hint="id"
        android:inputType="textPersonName"
        android:minHeight="48dp"
        android:textColorHint="#757575"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />


    <EditText
        android:id="@+id/input_nick"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="50dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="50dp"
        android:autofillHints=""
        android:ems="10"
        android:hint="name"
        android:inputType="textPersonName"
        android:minHeight="48dp"
        android:textColorHint="#757575"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/input_pwd" />


    <Button
        android:id="@+id/singUpBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="50dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="50dp"
        android:onClick="ClickButton1"
        android:text="joinbutton"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/input_nick"
        tools:ignore="DuplicateSpeakableTextCheck,TouchTargetSizeCheck" />

</androidx.constraintlayout.widget.ConstraintLayout>

위의 xml코드를 입력하고 실행해보면 아래 그림과 같은 레이아웃이 나옵니다.

activity_main.xml

간단하게 전송 폼을 만들어 준 다음에 웹서버로 넘겨주는 MainActivity.java 코드입니다.

package org.techtown.topython;

import androidx.appcompat.app.AppCompatActivity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

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

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private static final String urls = "웹 서버 주소"; // flask 호출 url
    private TextView input_id, input_pwd, input_nick; // 아이디 비밀번호 이름 받아오기위한 변수

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        input_id = findViewById(R.id.input_id);
        input_pwd = findViewById(R.id.input_pwd);
        input_nick = findViewById(R.id.input_nick);
    }

    public void ClickButton1(View v){ // 버튼클릭 리스너
        sendServer();
    }

    public void sendServer(){ // 서버로 전송하기위한 함수
        class sendData extends AsyncTask<Void, Void, String> { // 쓰레드 만들기

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
            }

            @Override
            protected void onProgressUpdate(Void... values) {
                super.onProgressUpdate(values);
            }

            @Override
            protected void onCancelled(String s) {
                super.onCancelled(s);
            }

            @Override
            protected void onCancelled() {
                super.onCancelled();
            }

            @Override
            protected String doInBackground(Void... voids) {

                try {
                    OkHttpClient client = new OkHttpClient();
                    // okHttpClient 호출
                    JSONObject jsonInput = new JSONObject();
                    // Json객체 생성
                    jsonInput.put("userID",  input_id.getText().toString());
                    jsonInput.put("userPassword",  input_pwd.getText().toString());
                    jsonInput.put("userName", input_nick.getText().toString());
                    // json객체에 데이터 추가

                    RequestBody reqBody = RequestBody.create(
                            jsonInput.toString(),
                            MediaType.parse("application/json; charset=utf-8")
                    );

                    Request request = new Request.Builder()
                            .post(reqBody)
                            .url(urls)
                            .build();

                    Response responses = null;
                    responses = client.newCall(request).execute();
                    System.out.println(responses.body().string());

                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
        }
        sendData sendData = new sendData();
        sendData.execute();
        // 웹서버에 데이터 전송
    }
}

위의 코드까지 입력을 마치셨다면, 안드로이드에서 해야 할 작업은 마무리 되었습니다.

다음은 파이썬 flask로 요청된 데이터를 가져와서 MySQL에 추가하는 작업을 해보겠습니다.

반응형
Comments