第五週週一(安卓端連線服務端)

a_true發表於2024-03-25

學會了安卓連線服務端的方法,使用OKhttp3

服務端程式碼:

package com.example.okhttp3;

import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;

@WebServlet("/api/hello")
public class HelloServlet extends HttpServlet {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            System.out.println("已連線");


             // 獲取客戶端的基本資訊
             String clientAddress = request.getRemoteAddr();
             String requestMethod = request.getMethod();
             String requestURI = request.getRequestURI();

             // 列印訪問資訊到控制檯
             System.out.println("Client Address: " + clientAddress);
             System.out.println("Request Method: " + requestMethod);
             System.out.println("Request URI: " + requestURI);


            String useSSL = request.getParameter("useSSL");
            String message;

            if (useSSL != null && useSSL.equals("true")) {
                message = "Hello, this is an API endpoint with SSL enabled!";
            } else {
                message = "Hello, this is an API endpoint with SSL disabled!";
            }

            // 構造一個包含 message 的 JSON 響應
            String jsonResponse = objectMapper.writeValueAsString(new ApiResponse(message));

            response.setContentType("application/json");
            response.getWriter().println(jsonResponse);
        } catch (Exception e) {

            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    // 響應資料的 POJO 類
    private static class ApiResponse {
        private final String message;

        public ApiResponse(String message) {
            this.message = message;
        }

        public String getMessage() {
            return message;
        }
    }
}

安卓端程式碼:

package com.example.okhttp3;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.google.gson.Gson;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private OkHttpClient client = new OkHttpClient();
    private TextView textView;

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

        // 關聯佈局檔案中的 TextView
        textView = findViewById(R.id.textView);

        // 建立一個請求
        Request request = new Request.Builder()
                .url("http://192.168.227.177:8080/api/hello?useSSL=true")
                .build();

        // 發起非同步請求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("連線", "連線失敗");
                // 處理連線失敗的情況
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("連線", "連線成功");
                // 處理連線成功的情況
                if (response.isSuccessful()) {
                    // 從響應中獲取資料
                    String responseData = response.body().string();
                    // 解析JSON資料並更新UI
                    updateUIWithResponse(responseData);
                } else {
                    // 處理響應失敗的情況
                    updateUIWithError();
                }
            }
        });
    }

    // 更新UI顯示響應資料
    private void updateUIWithResponse(final String responseData) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // 使用 Gson 解析 JSON 資料為 ApiResponse 物件
                Gson gson = new Gson();
                ApiResponse apiResponse = gson.fromJson(responseData, ApiResponse.class);
                // 設定 TextView 顯示解析後的訊息
                textView.setText(apiResponse.getMessage());
            }
        });
    }

    // 更新UI顯示連線失敗訊息
    private void updateUIWithError() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // 設定 TextView 顯示連線失敗訊息
                textView.setText("連線失敗");
            }
        });
    }
}

相關文章