Android 步驟 2 非同步伺服器請求

PayPal Developer Github 儲存庫中提供了此應用程式的完整示例程式碼(Android +節點伺服器)。

此時已點選 PayPal 未來付款按鈕,我們有來自 PayPal SDK 的身份驗證程式碼和後設資料 ID,我們需要將這些程式碼傳遞到我們的伺服器以完成將來的付款流程。

在下面的後臺流程中,我們正在做一些事情:

  • 我們設定了伺服器為 http://10.0.2.2:3000/fpstore 的 URI,它正在命中我們在 localhost 上執行的伺服器的/fpstore 端點。
  • 然後將設定將要傳送的 JSON 物件,其中包含身份驗證程式碼和後設資料 ID。
  • 然後建立連線。在成功請求(200/201 範圍)的情況下,我們可以期待從伺服器返回響應。我們讀了那個回覆,然後又回來了。
  • 最後,我們設定了 onPostExecute(...) 方法來處理返回的伺服器字串。在這個例子的情況下,它只是記錄。
public class ServerRequest extends AsyncTask<String, Void, String> {
    protected String doInBackground(String[] params){
        HttpURLConnection connection = null;
        try{
            //set connection to connect to /fpstore on localhost
            URL u = new URL("http://10.0.2.2:3000/fpstore");
            connection = (HttpURLConnection) u.openConnection();
            connection.setRequestMethod("POST");

            //set configuration details
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "application/json");
            connection.setAllowUserInteraction(false);
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(10000);

            //set server post data needed for obtaining access token
            String json = "{\"code\": \"" + params[0] + "\", \"metadataId\": \"" + params[1] + "\"}";
            Log.i("JSON string", json);

            //set content length and config details
            connection.setRequestProperty("Content-length", json.getBytes().length + "");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);

            //send json as request body
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(json.getBytes("UTF-8"));
            outputStream.close();

            //connect to server
            connection.connect();

            //look for 200/201 status code for received data from server
            int status = connection.getResponseCode();
            switch (status){
                case 200:
                case 201:
                    //read in results sent from the server
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = bufferedReader.readLine()) != null){
                        sb.append(line + "\n");
                    }
                    bufferedReader.close();

                    //return received string
                    return sb.toString();
            }

        } catch (MalformedURLException ex) {
            Log.e("HTTP Client Error", ex.toString());
        } catch (IOException ex) {
            Log.e("HTTP Client Error", ex.toString());
        } catch (Exception ex) {
            Log.e("HTTP Client Error", ex.toString());
        } finally {
            if (connection != null) {
                try{
                    connection.disconnect();
                } catch (Exception ex) {
                    Log.e("HTTP Client Error", ex.toString());
                }
            }
        }
        return null;
    }

    protected void onPostExecute(String message){
        //log values sent from the server - processed payment
        Log.i("HTTP Client", "Received Return: " + message);
    }
}