본문 바로가기
📱Web & Mobile/AndroidStudio

[AndroidStudio] 외부 API호출 (chatbot)

by inbeom 2023. 8. 20.
728x90
  • Chatbot API 코드
from utils import Api_key
from data import get_data
from learning import learn_data

from flask import Flask, request, jsonify, render_template

import sys
import openai
import json

application = Flask(__name__)

# key
openai.api_key = Api_key.openAI_key

# 챗봇 API 매핑 (POST)
@application.route("/", methods=['POST'])
def chatbot():
    try:
        request_data = request.get_json()
        user_input = request_data['user_input']
        response = learn_data(get_data.learn_data + [{"user": user_input, "ai": ""}])
        return jsonify({"racle": response})
    
    except:
        return jsonify({"error": "네트워크에 문제가 발생했습니다. 다시 시도해주세요."})

# 도움말 및 설명
@application.route("/help")
def chatbot_help():
    return render_template('help.html')
    

# 앱 실행
if __name__ == "__main__":
    application.debug = True
    application.run(host='0.0.0.0', port=int(sys.argv[1]))

 

💡 Flask(Python)로 개발하여 구름 IDE에 올려둔 chatbotAPI를 안드로이드에서 요청 및 응답.

조건

  • POST로 요청하며, Content-Type", "application/json타입을 세팅한다.
  • 요청 prameter는 JSON타입("user_input" : "현재 날씨 알려줘")으로 생성해서 보낸다.
  • 응답 시 JSON타입으로 parsing하여 전달 받는다.

Request Method

// chatbotAPI 요청
    private String chatbotTest(String userInput) throws Exception {
        try {
            URL url = new URL("<https://chatbot-api.run.goorm.site/>");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setDoOutput(true);

            JSONObject data = new JSONObject();
            data.put("user_input", userInput);

            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
            out.write(data.toString());
            out.flush();
            out.close();

            String temp = "";
            String content = "";
            InputStream responseBody = conn.getInputStream();
            InputStreamReader responseBodyReader =
                    new InputStreamReader(responseBody, "UTF-8");
            BufferedReader br = new BufferedReader( responseBodyReader );
            while ((temp = br.readLine()) != null) {
                content += temp;
            }
            JSONObject responseJson = new JSONObject(content);
            Log.d("chatGPT 응답", responseJson.toString(2));
            br.close();

            return responseJson.toString(2);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

Method 호출

new Thread(new Runnable() {
                    String result = "";
                    @Override
                    public void run() {
                        try {
                            result = chatbotTest(userInput);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        (ChatbotActivity.this).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tvResponse.setText(result);
                            }
                        });
                    }
                }).start();

안드로이드에서는 메인 스레드에서 네트워크 작업을 수행하지 않도록 제한하고 있기 때문에, 네트워크 작업은 별도의 스레드에서 수행해야 한다.

 

728x90

'📱Web & Mobile > AndroidStudio' 카테고리의 다른 글

[AndroidStudio] PHP 외부 DB연결  (0) 2023.08.20
[AndroidStudio] TMap API  (0) 2023.08.20
[AndroidStudio] SQLite  (0) 2023.08.20
[AndroidStudio] RecyclerView  (0) 2023.08.20
[AndroidStudio] Fragment  (0) 2023.08.20