簡體   English   中英

如何讓這個 iOS Http Post 請求工作?

[英]How to get this iOS Http Post Request to work?

我正在使用 Firebase Cloud Functions 和 Paypal 在我的應用程序中為司機設置付款流程。 要發布的 url 是 Firebase 中實際雲函數的 url:

https://us-central1-ryyde-sj.cloudfunctions.net/payout

Firebase 函數屏幕截圖

嘗試發送 HTTP Post 請求時,它似乎不起作用。 請參閱下面的payoutRequest()響應代碼:

支付請求()

let email = txtPayoutEmail.text!
    let uid = self.uid!
    
    // Prepare URL:
    let url = URL(string: "https://us-central1-ryyde-sj.cloudfunctions.net/payout")
    guard let requestUrl = url else { fatalError() }
    
    // Prepare URL Request Object:
    var request = URLRequest(url: requestUrl)
    request.httpMethod = "POST"
    
    // Set HTTP Request Headers
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.setValue("Your Token", forHTTPHeaderField: "Authorization")
    request.setValue("no-cache", forHTTPHeaderField: "cache-control")

    print("request = \(request)")
    
    // HTTP Request Parameters which will be sent in HTTP Request Body:
    let postString = "uid=\(uid)&email=\(email)"
    print("postString = \(postString)")
     
    // Set HTTP Request Body
    request.httpBody = postString.data(using: String.Encoding.utf8)
    
    // Perform HTTP Request
    let task = URLSession.shared.dataTask(with: request) { (data, response, error ) in
        
        print("data: \(String(describing: data))")
        print("response: \(String(describing: response))")
        print("error: \(String(describing: error))")
        
        if let response = response as? HTTPURLResponse {
            // Read all HTTP Response Headers
            print("All headers: \(response.allHeaderFields)")
            // Read a specific HTTP Response Header by name
            if #available(iOS 13.0, *) {
                print("Specific header: \(response.value(forHTTPHeaderField: "Content-Type") ?? " header not found")")
            } else {
                // Fallback on earlier versions
            }
        }
        
        // Check for Errors
        if let error = error {
            print("Error took place \(error)")
            return
        }
        
        // Convert HTTP Response Data to a String
        if let data = data, let dataString = String(data: data, encoding: .utf8) {
            print("Response data string: \(dataString)")
        }
    }
    
    task.resume()

回復

request = https://us-central1-ryyde-sj.cloudfunctions.net/payout
postString = uid=kv8JRVBwAfS1tgD04lNeM9esVzI2&email=myiosapp@me.com
data: Optional(138 bytes)
response: Optional(<NSHTTPURLResponse: 0x6000037d1c20> { URL: https://us-central1-ryyde-sj.cloudfunctions.net/payout } { Status Code: 400, Headers {
"Content-Length" =     (
    138
);
"Content-Type" =     (
    "text/html; charset=utf-8"
);
Date =     (
    "Thu, 17 Sep 2020 01:00:50 GMT"
);
Server =     (
    "Google Frontend"
);
"alt-svc" =     (
    "h3-Q050=\":443\"; ma=2592000,h3-29=\":443\"; ma=2592000,h3-27=\":443\"; ma=2592000,h3-T051=\":443\"; ma=2592000,h3-T050=\":443\"; ma=2592000,h3-Q046=\":443\"; ma=2592000,h3-Q043=\":443\"; ma=2592000,quic=\":443\"; ma=2592000; v=\"46,43\""
);
"content-security-policy" =     (
    "default-src 'none'"
);
"function-execution-id" =     (
    cmrwbktlroxl
);
"x-cloud-trace-context" =     (
    "a85aaacd578e60690581aa64ead13b23;o=1"
);
"x-content-type-options" =     (
    nosniff
);
"x-powered-by" =     (
    Express
);
} })
error: nil
All headers: [AnyHashable("content-security-policy"): default-src 'none', 
AnyHashable("Date"): Thu, 17 Sep 2020 01:00:50 GMT, AnyHashable("alt-svc"): h3-Q050=":443"; 
ma=2592000,h3-29=":443"; ma=2592000,h3-27=":443"; ma=2592000,h3-T051=":443"; ma=2592000,h3- 
T050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; 
ma=2592000; v="46,43", AnyHashable("Content-Type"): text/html; charset=utf-8, 
AnyHashable("Content-Length"): 138, AnyHashable("x-cloud-trace-context"): 
a85aaacd578e60690581aa64ead13b23;o=1, AnyHashable("Server"): Google Frontend, 
AnyHashable("x-powered-by"): Express, AnyHashable("x-content-type-options"): nosniff, 
AnyHashable("function-execution-id"): cmrwbktlroxl]
Specific header: text/html; charset=utf-8
Response data string: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Bad Request</pre>
</body>
</html>

如果請求成功,那么它將顯示在以下鏈接的 PayPal 沙盒通知中,但事實並非如此。

PayPal 開發者通知鏈接

我在 PayPal HTTP 請求方面沒有太多經驗。

我已經做了與我在這里嘗試做的相同的事情,但是在 Android 中它運行良好,所以我知道這應該可以工作,而不是 Post Request (我嘗試使用在線示例來匹配我在 Android 應用程序中的內容)

編輯

更新的payoutRequest():

** ** 中的代碼是新代碼

let email = txtPayoutEmail.text!
    let uid = self.uid!

    // Prepare URL:
    let url = URL(string: "https://us-central1-ryyde-sj.cloudfunctions.net/payout")
    guard let requestUrl = url else { fatalError() }

    // Prepare URL Request Object:
    var request = URLRequest(url: requestUrl)
    request.httpMethod = "POST"

    // Set HTTP Request Headers
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.setValue("Your Token", forHTTPHeaderField: "Authorization")
    request.setValue("no-cache", forHTTPHeaderField: "cache-control")

    print("request = \(request)")

    // HTTP Request Parameters which will be sent in HTTP Request Body:
    **let body = ["uid": uid, "email": email]** 
    print("body = \(body)")

    // Set HTTP Request Body
    **request.httpBody = try? JSONSerialization.data(withJSONObject: body, options: [])**

    // Perform HTTP Request
    let task = URLSession.shared.dataTask(with: request) { (data, response, error ) in

        print("data: \(String(describing: data))")
        print("response: \(String(describing: response))")
        print("error: \(String(describing: error))")

        if let response = response as? HTTPURLResponse {
            // Read all HTTP Response Headers
            print("All headers: \(response.allHeaderFields)")
            // Read a specific HTTP Response Header by name
            if #available(iOS 13.0, *) {
                print("Specific header: \(response.value(forHTTPHeaderField: "Content-Type") ?? " header not found")")
            } else {
                // Fallback on earlier versions
            }
        }

        // Check for Errors
        if let error = error {
            print("Error took place \(error)")
            return
        }

        // Convert HTTP Response Data to a String
        if let data = data, let dataString = String(data: data, encoding: .utf8) {
            print("Response data string: \(dataString)")
        }
    }

    task.resume()

回復:

request = https://us-central1-ryyde-sj.cloudfunctions.net/payout
body = ["uid": "kv8JRVBwAfS1tgD04lNeM9esVzI2", "email": "driver@ryyde.com"]
data: Optional(0 bytes)
response: Optional(<NSHTTPURLResponse: 0x600001f0d6a0> { URL: https://us-central1-ryyde-sj.cloudfunctions.net/payout } { Status Code: 200, Headers {
    "Content-Length" =     (
        0
    );
    "Content-Type" =     (
        "text/html"
    );
    Date =     (
        "Thu, 17 Sep 2020 04:41:29 GMT"
    );
    Server =     (
        "Google Frontend"
    );
    "alt-svc" =     (
        "h3-29=\":443\"; ma=2592000,h3-27=\":443\"; ma=2592000,h3-T051=\":443\"; ma=2592000,h3-T050=\":443\"; ma=2592000,h3-Q050=\":443\"; ma=2592000,h3-Q046=\":443\"; ma=2592000,h3-Q043=\":443\"; ma=2592000,quic=\":443\"; ma=2592000; v=\"46,43\""
    );
    "function-execution-id" =     (
        cmrwtq89fdsr
    );
    "x-cloud-trace-context" =     (
        "f3fe884ca8499e7a10c7081ce222876e;o=1"
    );
    "x-powered-by" =     (
        Express
    );
} })
error: nil
All headers: [AnyHashable("Content-Length"): 0, AnyHashable("x-cloud-trace-context"): f3fe884ca8499e7a10c7081ce222876e;o=1, AnyHashable("Server"): Google Frontend, AnyHashable("x-powered-by"): Express, AnyHashable("function-execution-id"): cmrwtq89fdsr, AnyHashable("alt-svc"): h3-29=":443"; ma=2592000,h3-27=":443"; ma=2592000,h3-T051=":443"; ma=2592000,h3-T050=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43", AnyHashable("Date"): Thu, 17 Sep 2020 04:41:29 GMT, AnyHashable("Content-Type"): text/html]
Specific header: text/html
Response data string: 

編輯 2

當我運行我的代碼時,我檢查了 firebase/functions 中的函數日志(從下往上讀取 - 函數活動似乎沒問題)

功能 1

功能 2

編輯 3 - 查爾斯會話結果

URL https://us-central1-ryyde-sj.cloudfunctions.net Status 正在發送請求正文... 注意事項 在會話被清除之前交易開始,在會話清除之前傳輸的正文內容尚未被捕獲 響應代碼 200 連接已建立 協議 HTTP/1.1 TLS TLSv1.2 (TLS_AES_128_GCM_SHA256) 協議 TLSv1.2 會話恢復 是密碼套件 TLS_AES_128_GCM_SHA256 ALPN - 客戶端證書 - 服務器證書 - 擴展方法 CONNECT 保持活動 無內容類型客戶端地址 127.0.0.0.15 遠程地址 127.0.0.0.15 遠程地址.cloudfunctions.net/216.239.36.54:443 標簽 - 連接 WebSockets - 計時大小請求 1.77 KB(1,817 字節)響應 1.35 KB(1,379 字節)

編輯 4 - Android 代碼

private void payoutRequest() {

    progress = new ProgressDialog(this);
    progress.setTitle("Processing your payout ...");
    progress.setMessage("Please Wait .....");
    progress.setCancelable(false);
    progress.show();

    // HTTP Request ....
    final OkHttpClient client = new OkHttpClient();

    // in json - we need variables for the hardcoded uid and Email
    JSONObject postData = new JSONObject();

    try {
        postData.put("uid", FirebaseAuth.getInstance().getCurrentUser().getUid());
        postData.put("email", mPayoutEmail.getText().toString());

    } catch (JSONException e) {
        e.printStackTrace();
    }

    // Request body ...
    RequestBody body = RequestBody.create(MEDIA_TYPE, postData.toString());

    // Build Request ...
    final Request request = new Request.Builder()
            .url("https://us-central1-ryyde-sj.cloudfunctions.net/payout")
            .post(body)
            .addHeader("Content-Type", "application/json")
            .addHeader("cache-control", "no-cache")
            .addHeader("Authorization", "Your Token")
            .build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            // something went wrong right off the bat
            progress.dismiss();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            // response successful ....
            // refers to response.status('200') or ('500')
            int responseCode = response.code();
            if (response.isSuccessful()) {
                switch(responseCode) {
                    case 200:
                        Snackbar.make(findViewById(R.id.layout),
                                "Payout Successful!", Snackbar.LENGTH_LONG)
                                .show();
                        break;

                    case 500:
                        Snackbar.make(findViewById(R.id.layout),
                                "Error: no payout available", Snackbar
                                        .LENGTH_LONG).show();
                        break;

                    default:
                        Snackbar.make(findViewById(R.id.layout),
                                "Error: couldn't complete the transaction",
                                Snackbar.LENGTH_LONG).show();
                        break;
                }

            } else {
                Snackbar.make(findViewById(R.id.layout),
                        "Error: couldn't complete the transaction",
                        Snackbar.LENGTH_LONG).show();
            }

            progress.dismiss();
        }
    });
}

嘗試這個:

    let body = ["uid": uid,
                "email": email]
     
    request.httpBody = try? JSONSerialization.data(withJSONObject: body, options: [])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM