I am using okhttp 4.0.1 in an Android app and there is a significant delay when receiving the response, particularly the headers. This adds a significant delay time to the users (ranging around 2-5 seconds) per request sent. The time delay is measured using okhttp's EventListenerfrom here https://square.github.io/okhttp/events/
This code is already placed inside an AsyncTask. Note that the delay happens after mCall?.execute
val mBuilder = Request.Builder()
val url = ....
// Add URL
mBuilder.url(url) // Request.Builder
// Request
val req = mBuilder.build()
// Call
var resp: Response? = null
var code = RESPSTATUS_IOEXC
var body = ""
try {
// Execute the call
mCall = mClient.newCall(req)
resp = mCall?.execute()
code = resp?.code?: 0
body = resp?.body?.string()?: ""
} catch (e: ConnectException) {
e.printStackTrace()
code = RESPSTATUS_CONNECTION_FAILED
} catch (e: SocketTimeoutException) {
e.printStackTrace()
code = RESPSTATUS_TIMEOUT
} catch (e: IOException) {
e.printStackTrace()
code = RESPSTATUS_IOEXC
} catch (e: IllegalStateException) {
e.printStackTrace()
code = RESPSTATUS_ALREADY_EXEC
} catch (e: CertificateException) {
e.printStackTrace()
code = RESPSTATUS_INVALID_CERT
} finally {
resp?.close()
}
One of the example messages showing the delay (3s delay retrieving response headers):
[1] dns started!
[1] dns ended!
[1] connect started!
[29] secure connect started!
[46] secure connect ended!
[46] connect ended!
[46] connection acquired!
[46] request headers started!
[47] request headers ended!
[47] response headers started!
[3676] response headers ended!
[3676] response body started!
[3702] response body ended!
[3704] connection released!
[3704] call ended!
Sample of the response headers I am getting
------ header(Server): nginx/1.10.3 (Ubuntu)
------ header(Date): Thu, 08 Aug 2019 15:08:02 GMT
------ header(Content-Type): application/json
------ header(Content-Length): 33071
------ header(Connection): close
------ header(Vary): Content-Type
------ header(Strict-Transport-Security): max-age=15552000; includeSubDomains; preload;
Our iOS team has called the URLs given without any considerable delay (1-2s max), so I do not know if the problem lies in the code or the server itself.
Any help is appreciated. Thanks before
Related
I'm using Retrofit to make some requests to the API, and when I receive back the response it's usually received from the API in this format if the request is successful
Successful Response
{
"success": 1,
"error": [],
"data": [
// Some data..
]
}
And if there is an error, the response will go like this
Unsuccessful Response
{
"success": 0,
"error": [
"Password is incorrect"
],
"data": []
}
The problem now in case there is an unsuccessful request, it comes with error code 403, so Retrofit classifies it as an Exception and throws an HttpException, then i have no way to catch the password is incorrect message attached in the json response.
Is there any way I still can get the body response even if there is an HttpException?
Update
This is the sample code I'm using
ViewModel
viewModelScope.launch {
try {
val result = myApi.request(requestParam)
}catch (e: HttpException){
// Log the error
}
}
Well, I figured out a way to get back the response from the passed exception.
As I said in the question, this is the code I'm using
Old code sample
viewModelScope.launch {
try {
val result = myApi.request(requestParam)
}catch (e: HttpException){
// Log the error
}
}
However, I didn't know that the response body is passed with the exception, and you can receive it as a string using the errorBody() method as follows.
New code sample
viewModelScope.launch {
try {
val result = myApi.request(requestParam)
}catch (e: HttpException){
val response = e.response()?.errorBody()?.string()
}
}
And from there you can manipulate this string to extract the error message.
I am sending a POST request to Firebase Cloud Messaging servers using the endpoint https://fcm.googleapis.com/v1/projects/{PROJECT_NAME}/messages:send so as to send notifications to my app. The problem is i am getting an error 401, AUTHENTICATION ERROR. I have gone through their doc https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages/send?apix=true many times and i can't seem to understand why i am getting this error. I tried testing the endpoint with the Google API explorer on the page and it works fine. Notification is sent to my app. However, sending this same POST request in my code with volley fails with the follow error, in JSON:
{
"error": {
"code": 401,
"message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"status": "UNAUTHENTICATED"
}
}
Here's what i did:
val FCM_POST = "https://fcm.googleapis.com/v1/projects/${Constants.PROJECT_NAME}/messages:send"
val map = mapOf("message" to
mapOf("notification" to
mapOf("title" to "test title",
"body" to "test body")),
"topic" to "testTopic")
val request = object : JsonObjectRequest(
Method.POST,
FCM_POST,
JSONObject(map), {
showDialog.log(TAG, "sendMedicalTipsNotification response: $it")
}, {
val networkResponse = it.networkResponse
if (networkResponse?.data != null) {
val jsonError = String(networkResponse.data)
try {
val jsonObject = JSONObject(jsonError)
showDialog.log(TAG, "sendMedicalTipsNotification error: $jsonObject")
} catch (e: JSONException) {
showDialog.log(TAG, "sendMedicalTipsNotification error: $e")
}
}
}) {
override fun getHeaders(): MutableMap<String, String> {
return mutableMapOf("Authorization" to "Bearer ${Constants.MY_PROJECT_CLOUD_CONSOLE_CLIENT_ID}",
"Content-Type" to "application/json")
}
}
Volley.newRequestQueue(ctx).add(request)
}
As you can see i'm sending my CLIENT_ID and Content Type in request header. I really don't know why i am getting this error
I am setting up a payout process for a driver in my app with Firebase Cloud Functions and Paypal. The url to be posted is the url of the actual cloud function in Firebase:
https://us-central1-ryyde-sj.cloudfunctions.net/payout
When trying to send an HTTP Post Request, it doesn't seem to be working. See the payoutRequest() and the Response code below:
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()
Response
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>
If the request is successful, then it would show up in the PayPal Notifications for PayPal Sandbox at the below link, but it isn't.
PayPal developer notifications link
I don't have much experience in PayPal HTTP requests.
I have done the same thing as I am trying to do here but in Android and it works perfectly so I know this should work, other than the Post Request (I tried using examples online to match what i had for the Android app)
Edit
updated payoutRequest():
Code surrounded in ** ** is new code
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()
Response:
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:
EDIT 2
When I run my code, I check the function logs in firebase/functions (read from bottom up - seems to go ok with the function activity)
EDIT 3 - Charles Session results
URL https://us-central1-ryyde-sj.cloudfunctions.net Status Sending
request body… Notes Transaction began prior to session being cleared,
body content transmitted before the session clear has not been
captured Response Code 200 Connection established Protocol HTTP/1.1
TLS TLSv1.2 (TLS_AES_128_GCM_SHA256) Protocol TLSv1.2 Session
Resumed Yes Cipher Suite TLS_AES_128_GCM_SHA256 ALPN - Client
Certificates - Server Certificates - Extensions Method CONNECT Kept
Alive No Content-Type Client Address 127.0.0.1:57209 Remote
Address us-central1-ryyde-sj.cloudfunctions.net/216.239.36.54:443
Tags - Connection WebSockets - Timing Size Request 1.77 KB (1,817
bytes) Response 1.35 KB (1,379 bytes)
EDIT 4 - Android code
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();
}
});
}
try this:
let body = ["uid": uid,
"email": email]
request.httpBody = try? JSONSerialization.data(withJSONObject: body, options: [])
I am facing a problem with coding my first Android-App.
I want to build the login-system of the app around my existing webserver/webinterface.
I am using the Fuel-Library, and as far as I can tell, the GET Requests are working fine.
The problem is the response. When I print it out, everything is see is some information about the request itself, but the printed echo from PHP isn't showing up anywhere.
Response printed out:
I/System.out: <-- 200 https://...hidden :)
I/System.out: Response : OK
Length : -1
Body : test
Headers : (11)
Connection : Keep-Alive
Date : Mon, 30 Mar 2020 18:06:39 GMT
X-Android-Selected-Protocol : http/1.1
Server : Apache
X-Powered-By : PHP/7.3.5, PleskLin
Content-Type : text/html; charset=UTF-8
X-Android-Received-Millis : 1585591597000
Vary : Accept-Encoding
X-Android-Response-Source : NETWORK 200
X-Android-Sent-Millis : 1585591596960
Keep-Alive : timeout=5, max=100
The same is happening with POST Requests.
Here is my Kotlin-Code:
val url = "https://myserver.com/testlogin.php?username=".plus(username.toString()).plus("&password=").plus(password.toString())
url.httpGet().responseString{
request, response, result ->
Toast.makeText(this#MainActivity, result.toString(), Toast.LENGTH_LONG).show()
}
And the PHP Code on the Webserver:
<?php $username = $_GET["username"]; $password = $_GET["password"]; echo $username; ?>
I am searching for more than 7 hours now. send help
Try this
url.httpGet().responseString { request, response, result ->
when (result) {
is Result.Failure -> {
val ex = result.getException()
println(ex)
}
is Result.Success -> {
val data = result.get()
println(data)
}
}
}
Official documentation
I just found the problem:
val data = result.get() println(data)
prints the response string of the php file.
From my research, there isn't much help translating Android code to Swift code. With some help, we were able to translate or convert some of the code but it's not quite finished. When I run the code, I get an error:
Response could not be serialized, input data was nil or zero length.
responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)
Android code needing converting to Swift code:
public static final MediaType MEDIA_TYPE = MediaType.parse("application/json");
ProgressDialog progress;
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-myapp.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();
}
});
}
Swift code used from the above Android code:
let url = "https://us-central1-myapp.cloudfunctions.net/payout"
let headers: HTTPHeaders = [
"Content-Type": "application/json",
"cache-control": "Your Token"]
Alamofire.request(url, method: .get, headers: headers).validate().responseJSON { (response) in
switch response.result {
case .success(let value):
// you fall here once you get 200 success code, because you use .validate() when you make call.
print(value)
// parse your JSON here.
let parameters : [String: Any] =
["uid": FIRAuth.auth()!.currentUser!.uid,
"email": self.paypalEmailText.text!]
let postData = try! JSONSerialization.data(withJSONObject: parameters, options: [])
case .failure(let error):
if response.response?.statusCode == 500 {
print("Error no payout available")
print(error.localizedDescription)
} else {
print("Error: couldn't complete the transaction")
print(error.localizedDescription)
}
}
}
How can I convert the Android code into the Swift code or discover what it is I am doing wrong? This code is used to post to the function I have created for Firebase.
Edit
With the help of supplied code in this post, I was able to come up with this code but it is still coming up with the same error:
===========Error===========
Error Code: 4
Error Messsage: Response could not be serialized, input data was nil or zero length.
response FAILURE: responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)
updated swift code
let url = "https://us-central1-myapp.cloudfunctions.net/payout"
let headers: HTTPHeaders = [
"Content-Type": "application/json",
"cache-control": "Your Token"]
let params : [String: Any] = [
"uid": FIRAuth.auth()!.currentUser!.uid,
"email": self.paypalEmailText.text!]
Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).validate().responseJSON { (response) in
switch response.result {
case .success(let JSON):
print("Success with JSON: \(JSON)")
if (response.result.value as? [String:AnyObject]) != nil {
// Access your response here
print(response.result.value!)
}
break
case .failure(let error):
if response.response?.statusCode == 500 {
print("Error no payout available")
print(print("Request failed with error: \(error.localizedDescription)"))
} else {
print("Error: couldn't complete the transaction")
print("\n\n===========Error===========")
print("Error Code: \(error._code)")
print("Error Messsage: \(error.localizedDescription)")
}
}
print("response \(response)")
}
EDIT #2
I edited my method:
let url = "https://us-central1-myapp.cloudfunctions.net/payout"
let headers: HTTPHeaders = [
"cache-control": "no-cache",
"Authorization": "Your Token",
"Content-Type": "application/json"]
let parameters : [String: Any] = [
"uid": uid,
"email": self.paypalEmailText.text!
]
Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).validate(statusCode: 200..<600).responseJSON { (response) in
print("Request: \(String(describing: response.request))") // original url request
print("Result: \(response.result)") // response serialization result
if response.response?.statusCode == 200 {
print("Success with JSON: \(String(describing: response.result.value))")
} else {
let error = (response.result.value as? [[String : AnyObject]])
print(error as Any)
}
print("response \(response)")
}
The response and print outs are:
Request: Optional(https://us-central1-myapp.cloudfunctions.net/payout)
Result: FAILURE
Success with JSON: nil
response FAILURE: responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)
Keep in mind, in my url, my app is not called "myapp" it is just there for protection.
I think there are two issues in the code:
In the Android code, you are setting the parameters uid and email in the request body, whereas in the Swift code, you are setting these parameters in the response body, which is wrong (because by the time you got the response, the request is already completed without the params).
If you want to set a body for the request, the HTTP method (the second parameter to Alamofire.request should be post instead of get.
What you need to do is set the parameters in the request body and set the HTTP method as post, as follows:
let parameters: [String: Any] =
["uid": FIRAuth.auth()!.currentUser!.uid,
"email": self.paypalEmailText.text!]
Alamofire.request(url, method:.post, parameters:parameters,
encoding: JSONEncoding.default, headers:headers)
Try it out and see if it works.
So I'd do it like this here:
let url = "https://us-central1-myapp.cloudfunctions.net/payout"
let headers: HTTPHeaders = [
"Content-Type": "application/json",
"cache-control": "Your Token"
]
Alamofire.request(url,
method: .get,
encoding: JSONEncoding.default,
headers: headers).responseJSON
{ response in
switch response.result {
case .success(let JSON):
print("Success with JSON: \(JSON)")
// parse your JSON here something like
if let json = response.result.value as? [String:AnyObject] {
// Access your response here
}
break
case .failure(let error):
print("Request failed with error: \(error)")
}
}
In the success part you should be able to access the JSON and are able to parse it. Can you comment how your reponse object looks like, then I'll comment how you parse it and access the correct elements. I can otherwise only guess.