My application does post request to url:
https://myserver.domain.com/authenticate/credentials
OkHttp client interceptor shows my headers:
11-17 10:10:56.780 3140-3304/com.myapp.debug D/OkHttp: Content-Type:
application/x-www-form-urlencoded
11-17 10:10:56.780 3140-3304/com.myapp.debug D/OkHttp: Content-Length:
187
11-17 10:10:56.781 3140-3304/com.myapp.debug D/OkHttp: Authorization:
Basic authorisationkeyfortest5430593045903495034905==
11-17 10:10:56.781 3140-3304/com.myapp.debug D/OkHttp:
email=testlogin%40gmail.com&password=test%4012&deviceId=1484564155&deviceLabel=Android%20SDK%20built%20for%20x86_64&deviceType=ANDROID&deviceVersion=23%20%28REL%29
I have created standalone WireMock server and I want redirect every POST request from my APP to my WireMock server. Thats why I have added *.JSON with request definition:
{
"request": {
"method": "POST",
"urlPattern": ".*"
},
"response": {
"proxyBaseUrl" : "https://myserver.domain.com/",
"additionalProxyRequestHeaders": {
"Authorization": "Basic authorisationkeyfortest5430593045903495034905== "
}
}
}
What I expect that should happen:
When I change basepath of my Http client from https://myserver.domain.com/ to http://myserveraddress.com/ - then every request from my app should go to my MockServer. And MockServer according to JSON above should proxy/forward that request to https://myserver.domain.com/ and return the same response - so everything should work fine.
What happens:
Each POST request returns status 200 but body is empty. (it should return authenticated user object)
Question: Is it possible to achieve that? Am I doing something wrong?
Try to add your body in "__files" folder and set path in "bodyFileName"
{
"request": {
"method": "POST",
"urlPattern": ".*"
},
"response": {
"proxyBaseUrl" : "https://myserver.domain.com/",
"additionalProxyRequestHeaders": {
"Authorization": "Basic authorisationkeyfortest5430593045903495034905== "
},
"bodyFileName":".*.json"
}
In JSON file put your answer. For example:
{
"errorCode": 0,
"errorMessage": "",
"result":
{
"filed1":"value",
"filed2":"value"
}
}
Related
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.
this is the code.
Future<http.Response> postRequest () async {
var url ='http://10.0.2.2:3000/api/message';
Map data = {
'message': '12345678901234567890'
};
//encode Map to JSON
var body = json.encode(data);
var response = await http.post(url,
headers: { "accept": "application/json", "content-type": "application/json" },
body: body
);
print("${response.statusCode}");
print("${response.body}");
return response;
}
postRequest();
// also tried this: headers: {"content-type":"application/json" },
In my python flask server, the post message is logging, but with empty body into it.
The flutter app is running on Android Virtual Device and the server is still running on http://0:0:0:0:3000/ and it's using request.get_json() in the method.
Using postman, everything works as expected on my server so I see the problem in the app.
postman details:
POST: http://localhost:3000/api/message
headers
KEY | VALUE
Content-Type | application/json
Body raw
{
"message": "opa"
}
also raised here: https://github.com/flutter/flutter/issues/39351
Try passing :
Future<http.Response> postRequest () async {
var url ='http://10.0.2.2:3000/api/message';
Map<String, String> data = { "message": "opa" };
var body = json.encode(data);
var response = await http.post(url,
headers: { "accept": "application/json", "content-type": "application/json" },
body: body
);
print(response.statusCode);
print(response.body);
return response;
}
postRequest().then((response){
print(response.body);
});
not sure if my finding is precious or not for community, but it seems that the URL was the problem. Everything works now, but I added a / in the end of the string in my flask app.
In Postman, I didn't have to do this. So if you have same problem, take care :)
The log from Flask server:
127.0.0.1 - - [30/Aug/2019 17:41:32] "POST /api/message/ HTTP/1.1" 200 -
opa
My Flask url is:
#app.route('/api/message/', methods=['POST'])
def function():
This is my end point :
#POST("v4/MyStore/data")
Observable<Headers> requestStore(#Body MyStoreRequest request);
I am trying to get response like this :
requestService.requestStore(request)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.computation())
.map(headers -> {
Log.d("Response",""+headers);
return headers;
}).subscribe(headers -> {
Log.d("Response",""+headers);
},
error -> {
Log.d("ERRRROOOR","Error");
});
I am getting error like below:
Exception: retrofit2.adapter.rxjava.HttpException: HTTP 403 Forbidden
While in postman I am getting response:
Connection →keep-alive
Content-Length →0
Content-Type →application/json; charset=utf-8
Date →Mon, 03 Sep 2018 18:47:30 GMT
MYid →f028df50-c8c5-4cce-92e7-70130345ba46
What I am doing wrong here?
You have to use a Response as your response model because your api is entering error stream in with a code 403
#POST("v4/MyStore/data")
Observable<Response<Void>> requestStore(#Body MyStoreRequest request);
now when you consume response
requestService.requestStore(request)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.computation())
.map(response -> {
Log.d("Response",""+response);
return response.header();
}).subscribe(headers -> {
Log.d("Response",""+headers);
},
error -> {
Log.d("ERRRROOOR","Error");
});
response.header() will return you the header you want even when your api fails
Probably you're missing headers in your API request from Android client. As per your comment, you're sending bearer token in Authorization headers.
So, you need to send bearer token along with request body like below
#Headers({
"Authorization: Bearer <your_bearer_token_here>", /* change token here */
"Content-Type: application/json"
})
#POST("v4/MyStore/data")
Observable<Headers> requestStore(#Body MyStoreRequest request);
Example,
#Headers({
"Authorization: Bearer ca0df98d-978c-410b-96ec-4e592a788c18",
"Content-Type: application/json"
})
#POST("v4/MyStore/data")
Observable<Headers> requestStore(#Body MyStoreRequest request);
In my app I'm using WebView. I'm trying to call POST method that cannot proceed my request.I get this error:
XMLHttpRequest cannot load https://*****/support/create_ticket.
Request header field Content-Type is not allowed by
Access-Control-Allow-Headers. at null:1
It's happening only in device with Jelley bean 4.2.2 in all the other OS it's work fine.
Thanks a lot for the help.
Add this to request headers:
Map<String, String> extraHeaders=new HashMap<>();
extraHeaders.put("Access-Control-Allow-Origin","*");
extraHeaders.put("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept");
You might need to add this too:
extraHeaders.put("Access-Control-Allow-Methods","POST");//you add more:"GET, POST, PUT"
--- Updated based on your code, here is the adjustment:
RestAPI.Groups = $resource('groups/:id', {
id: '#id'
}, {
get: {
method: "GET",
KalseferPrivateAPI: true,
interceptor: Interceptors.get
},
join: method: "POST",
KalseferPrivateAPI: true,
interceptor: Interceptors.post,
headers: {
'Access-Control-Allow-Origin:*',
'Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Accept',
'Access-Control-Allow-Methods:POST'
},
url: 'groups/join'
}, addMember: {
method: "POST",
KalseferPrivateAPI: true,
interceptor: Interceptors.post,
headers: {
'Access-Control-Allow-Origin:*',
'Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Accept',
'Access-Control-Allow-Methods:POST'
},
url: 'groups/:id/users/:users',
params: {
id: '#id',
users: '#users'
}
}
});
I hope that may help,'.
I was able make to make push notification is working. I tested it on REST.
POST
Host: android.googleapis.com/gcm/send
Content-Type: application/json
Authorization: key=**apiKey**
Cache-Control: no-cache
Postman-Token: b33c61dc-a779-9198-bd96-aaf6c24fac6c
{
"data": {
"message": "hello world"
},
"registration_ids" : ["**deviceToken**"]
}
and my device got notification. Now I'm struggling to make parse push working.
POST localhost:7002/server/push
X-Parse-Application-Id: SSShop
X-Parse-Master-Key: 123
Content-Type: application/json
{
"where": {},
"data": {
"alert": "hello world 123"
}
}
the output: { result: true }, but notification is not received on device. Trying send push notification via Parse Dashboard and got output like this:
verbose: sending push to 2 installations
verbose: sent push! 0 success, 0 failures.
server.js:
const instance = {
appId: 'SSShop',
port: 7002,
serverURL: 'http://localhost:7002/server',
masterKey: '123',
databaseURI: 'mongodb://docker/ssshop',
publicServerURL: 'http://localhost:7002/server',
mountPath: '/server',
verifyUserEmails: true,
appName: 'SSShop',
emailAdapter: {
module: 'parse-server-simple-mailgun-adapter',
options: {
fromAddress: 'XX',
domain: 'XX',
apiKey: 'XX'
}
},
push: {
android: {
senderId: "92014XXXXX",
apiKey: "**apiKey**"
}
}
}
package.json:
"parse": "~1.8.5",
"parse-dashboard": "~1.0.13",
"parse-server": "~2.2.11",
checking node_modules and got parse-server-push-adapter use version 1.0.4.