not getting response, how do i get response of retrofit image upload using bearer token - retrofit

this is the call of interface:
usersApi.uploadImage("Bearer $token", parts).enqueue(object :Callback{
override fun onResponse(call: Call, response: Response)
{
if (response.isSuccessful)
{
Toast.makeText(this#UserProfileActivity, response.body()?.pic_url, Toast.LENGTH_SHORT).show()
}
}
override fun onFailure(call: Call<UploadImageResponse>, t: Throwable) {
Toast.makeText(this#UserProfileActivity, "not getting response", Toast.LENGTH_SHORT).show()
}
})
this is my interface:
#Multipart
#POST("upload-profile-image")
fun uploadImage(
#Header("Authorization") token : String,
#Part image: MultipartBody.Part
): Call

Related

ClientException, and i can't print the returned value (the request body)

Alright i'm losing my mind here,
in my flutter app, i'm using this function to perform post requests :
Future<Map> postRequest(String serviceName, Map<String, dynamic> data) async {
var responseBody = json.decode('{"data": "", "status": "NOK"}');
try {
http.Response response = await http.post(
_urlBase + '$_serverApi$serviceName',
body: jsonEncode(data),
);
if (response.statusCode == 200) {
responseBody = jsonDecode(response.body);
//
// If we receive a new token, let's save it
//
if (responseBody["status"] == "TOKEN") {
await _setMobileToken(responseBody["data"]);
// TODO: rerun the Post request
}
}
} catch (e) {
// An error was received
throw new Exception("POST ERROR");
}
return responseBody;
}
The problems are :
I get a ClientException (Not every time)
In another class, I stored the result of this function in a variable, it's supposed to return a Future<Map<dynamic, dynamic>>, when i printed it it shows :
I/flutter ( 9001): Instance of 'Future<Map<dynamic, dynamic>>'
But when i run the same post request directly (without using a function) it worked, and it shows the message that i was waiting for.
note: in both cases (function or not), in the server side it was the same thing.
this is the function where i used the post request:
void _confirm() {
if (_formKey.currentState.saveAndValidate()) {
print(_formKey.currentState.value);
var v = auth.postRequest("se_connecter", _formKey.currentState.value);
print(v);
} else {
print(_formKey.currentState.value);
print("validation failed");
}
}
Well for the second problem, i just did these changes:
void _confirm() async {
and
var v = await auth.postRequest('se_connecter', _formKey.currentState.value);
and yes it is stupid.
For the exception, it was the ssl encryption that caused it, so i removed it from my backend.

Why am I getting null body values on my api request?

Context:
It's a .Net Core app
Using React, Redux, and Axios which finally makes the request.
Axios call:
// At this point I do have values on my request
// { "param1": 2021, "param2": "where the sidewalk ends" }
console.log(myRequest);
axios.post('api/myPath/create', myRequest, options)
.then(function (result) {
...
})
.catch(function (error) {
...
});
Api controller:
namespace myNamespaceApi
{
[Route("api/myPath/create")]
[ApiController]
public class MyCreateController : .....
{
[HttpPost]
[Authorize(Policy = ShouldBeCertainRole)]
public async Task<MyApiOperationResult<MyCreateResponseViewModel>> Post([FromBody] MyCreateRequestViewModel request)
{
try
{
.....
// at this point my request comes with null values
// { "param1": null, "param2": null }
}
catch (Exception ex)
{
....
}
}
}
}
So it is making the call, but not reaching the method with the values.
Any suggestions?

Http post request with body parameters not working

Recently I started developing a small application in Flutter. I have an issue with making a network request. I have tried the call in postman and there it work. But in Flutter I never managed to make it work, I have spent like 3 hours trying to understand what I am doing wrong.
Any help will be greatly appreciated.
#override
Future<String> login(common.LoginParameters loginParameters) async {
try {
final String loginURL = "https://test.example.eu/api/login";
LoginModel loginResult;
Map bodyParams = { "inlognaam" : loginParameters.username , "wachtwoord" : loginParameters.password, "code" : loginParameters.smsCode};
//await API call
http.Response httpResponse = await http.put( loginURL, body: json.encode(bodyParams));
if (httpResponse.statusCode == 200) {
// If server returns an OK response, parse the JSON
loginResult= LoginModel.fromJson(json.decode(httpResponse.body));
} else {
// If that response was not OK, throw an error.
throw Exception('Failed to load post');
}
// if logged in get token, Otherwise return error
if (loginResult.ingelogd) {
// read the token
saveToken(loginResult.response);
return "Ingelogd";
} else {
return loginResult.error;
}
}
on Exception catch(error) {
print("Todor " + error.toString());
return "Controleer uw internet verbinding en probeer opnieuw";
}
}
In Postman if I select Post request with body parameters
inlognaam : someUsername
wachtwoord : somePassword
code : someCode
Then I get a success response
I pass the parameters in the following way, maybe it can work for you:
var response = await http.post(
url,
headers:{ "Accept": "application/json" } ,
body: { "state": 1}, //key value
encoding: Encoding.getByName("utf-8")
);
Another thing, you say that in postman you make a post request, but in your code you have a put request, verify what is the correct method

How to send a POST request to Firebase Cloud Messaging API in Vapor

I am trying to make a POST request to a Firebase Notifications API using Vapor 1.5 and Firebase Legacy Protocol, but I get failure response.
response is JSON(node: Node.Node.object(["multicast_id":
Node.Node.number(5936281277445399934), "failure": Node.Node.number(0),
"canonical_ids": Node.Node.number(0), "results":
Node.Node.array([Node.Node.object(["message_id":
Node.Node.string("0:1527074314969790%c7ade8b9f9fd7ecd")])]),
"success": Node.Node.number(1)]))
EDIT
Making the request through POSTMan fails with error "The request was missing an Authentication Key (FCM Token)."
class FirebaseRequester {
let fcmLegacyServerKey = "AIzaSyDSuXXXXXXkCafTQay5_r8j3snvVos"
func sendNotification(payLoad: JSON) throws -> Response {
var response: Response?
do {
let responseFCM = try drop.client.post("https://fcm.googleapis.com/fcm/send",
headers: ["Content-Type":"application/json","Authorization": "key\(fcmLegacyServerKey)"],
query: [:],
body: payLoad.makeBody())
response = responseFCM
}catch let error {
let message = error.localizedDescription
logErr.prints(message: message)
throw Abort.custom(status: .badRequest, message: message)
}
guard let rsp = response?.json else {
let message = "no json received on line \(#line)"
drop.log.error(message)
logErr.prints(message: message)
throw Abort.custom(status: .badRequest, message: message)
}
print("rsp in json format is \(rsp)")
return response!
}//end of sendNotification()
}//end of class FirebaseRequester
//make another class here and initialize it with FirebaseRequester
//get data from Client App
// validate data
// finally, create the payLoad and call sendNotification(:)
//request should look like
{
"aps": {
"alert": "Breaking News!",
"sound": "default",
"link_url": "https://raywenderlich.com"
}
}
let fcmKeyToSendTo = "someDeviceTokenKeyReceivedFromClient_biHZNI-e9E53WEkCzrki"
let data = try Node(node: ["alert": "alert", "sound": "sound", "link_url": "https://www.someWebsite.com"])
var payLoadObj = try JSON(node: ["aps" : data])
payLoadObj["to"] = try JSON(node: fcmKeyToSendTo)
do {
let _ = try firebaseRequester.sendNotification(payLoad: payLoadObj)
}catch{
logErr.prints(message: error.localizedDescription)
}
let message = "notification Sent"
return try JSON(node:["success":message])
In sendNotification(payload:) I had a typo, I missed = after key. It should have been "key=\(fcmLegacyServerKey)"
In sendNotification(payload:), payLoad.makeBody should not be called, I should have just passed the JSON object payLoad as an argument to the .post request.
The JSON object of the notification was clearly badly formatted from the outset. The message type I wanted to send was notification, but I was passing in a key named aps. I should have passed key notification as shown below.
.
class FirebaseRequester {
let fcmLegacyServerKey = "AIzaSy....vVos"
func sendNotification(payLoad: JSON) throws -> Response {
var response: Response?
do {
let responseFCM = try drop.client.post("https://fcm.googleapis.com/fcm/send",
headers: ["Content-Type":"application/json","Authorization": "key=\(fcmLegacyServerKey)"],
query: [:],
body: payLoad
response = responseFCM
}catch let error {
let message = error.localizedDescription
logErr.prints(message: message)
throw Abort.custom(status: .badRequest, message: message)
}
guard let rsp = response?.json else {
let message = "no json received on line \(#line)"
drop.log.error(message)
logErr.prints(message: message)
throw Abort.custom(status: .badRequest, message: message)
}
return response!
}//end of sendNotification()
}//end of class FirebaseRequester
class TestRouteNow {
let firebaseRequester: FirebaseRequester
init(firebaseRequester: FirebaseRequester) {
self.firebaseRequester = firebaseRequester
}
func addRoutes(drop: Droplet) {
drop.post("test", "notif", handler: postNotification)
}
func postNotification(request: Request) throws -> ResponseRepresentable {
let fcmDevice = "someDeviceTokenReceivedFromClientApp"
let data = try Node(node: ["title": "title","body": "body", "sound": "default", "badge":"60"])
var payLoadObj = try JSON(node: ["notification": data])
payLoadObj["to"] = try JSON(node: fcmDevice)
do {
let _ = try firebaseRequester.sendNotification(payLoad: payLoadObj)
}catch{
logErr.prints(message: error.localizedDescription)
}
let message = "notification Sent"
return try JSON(node:["success":message])
}
}//end of class
// request body
{
"to" : "cQDtm_someDeviceTokenReceivedFromClient",
"priority":"high",
"notification": {
"title":"Booking Rescheduled",
"body": "Cancelled Booking 7830593, for Mon, 12 March",
"sound":"default",
"badge": "100"
}
}

ASP.NET return null or no connection from angular4

I am trying to send JSON string from angular to asp.net server. I tried two things to get this data from client side.
1st : I have following code from both server and client side. I am sending a json string, and I expected to receive at backend for what I sent. However, I am just getting this server error before even getting the data.
POST "url" 404 (not found)
{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:61476/api/testAPI/getData'.","MessageDetail":"No action was found on the controller 'getData' that matches the request."}
2nd : given that everything is same, i just added [FromBody] in my method like below. This doesn't return any server error and I am able to connect from my client side to server. However, I am getting my body message as null . I tried with Postman, but it seems that it works fine with Postman when I send same data.. I am aware that I can create some modelling in server code to match with my json string from client side, but I don't get why this doesn't work without modelling and also why connection fails without [FromBody].
All I need is to get JSON string from my client side. Can anyone please provide me advice on this?
public string getData([FromBody] string body)
angular
callServer(){
var json = {"name":"John Doe", "school": "A"};
let headers = new HttpHeaders();
headers.set('Content-Type', 'application/json');
this.appService.http.post('http://localhost:61476/api/testAPI/getData',
json,
{headers: headers})
.subscribe(data => {console.log(data), (err) => console.error("Failed! " + err);
})
}
server
namespace test.Controllers
{
public class testAPIController : ApiController
{
//
[HttpPost]
public string getData(string body)
{
try
{
Log.Info(string.Format("data {0}", body));
return "ok";
}
catch (Exception ex)
{
Log.Error(ex.Message);
return "error";
}
}
}}
Controller:
[HttpPost]
public string postData([FromBody]string body)
{
try
{
Log.Info(string.Format("data {0}", body));
return Json("ok");
}
catch (Exception ex)
{
Log.Error(ex.Message);
return "error";
}
}
Calling the server:
callServer() : Observable<string> {
var json = {"name":"John Doe", "school": "A"};
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
let apiUrl = 'http://localhost:61476/api/testAPI/postData';
return this.appService.http.post(`${this.apiUrl}`, json, options)
.map((res: Response) => res.json())
.catch(this.handleErrorObservable);
}
private handleErrorObservable(error: Response | any) {
console.error(error.message || error);
return Observable.throw(error.message || error);
}
Calling the service:
this._service.callServer()
.subscribe(
res => { console.log(res) },
err => { console.log(err) }
)
console.log(res/err) will be your response from the POST call. Sorry if misinterpreted your question but your question is a little hard to follow.
404 error is "not found". You must decorate your API Class
[Route("api/TestApi/[action]")]
public class testAPIController : ApiController
{
[HttpPost]
[HttpPost, ActionName("getData")]
public string getData([FromBody]string body)
{}
}

Resources