SWIFT 3 Post request with VIEWSTATE - asp.net

I need to log in example.com/mobile/shared/default.aspx by using POST request
How do i get current ViewState and sending it after?
That is what i tried
(Alamofire)
func webRequest()
{
let parameters: Parameters = [
"name": "name",
"password": "password",
"enter": "Enter",
]
Alamofire.request("http://example.ru/mobile/shared/default.aspx", parameters: parameters).responseJSON { response in
print(response.request) // original URL request
print(response.response) // HTTP URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
}

I'm using Alamofire like this:
let Parameters = [
"name": "name",
"password": "password",
"enter": "Enter"]
var json : JSON = nil
Alamofire.request(URLString, method: method, parameters: Parameters)
.responseJSON { response in
switch response.result {
case .success(let data):
json = JSON(data)
print(json)
case .failure(let error):
print("Request failed with error: \(error)")
}
}
}
So after that you can parse your json like this for example:
if json != nil {
let token = json["token"].stringValue
}
But all of that depend of your server request params, and request response from your server.
Hope I helped you, Peace

Related

XRay-Import json result file with Cloud Rest API call getting error "No project could be found with key 'null'."

We are trying to import test execution result in json format to xray Jira cloud by cloud Rest API call. After importing through Rest API call we are getting below error.
I gone through the solutions but couldn't got working solution.
{"error": "Error retrieving Project from Jira with key "null": No project could be found with key 'null'."}
Below is my code snippet:
public void postAPICall(){
File dataFile = new File("src/main/resources/Payloads/auth.json");
String url ="https://xray.cloud.getxray.app/api/v2/authenticate";
RequestSpecification request = RestAssured.given();
request.header("Content-Type", "application/json");
request.body(dataFile);
Response response = request.post(url);
ResponseBody body = response.getBody();
tokenResult=body.asString();
}
#Test
public void postCallUpdateTestResult(){
postAPICall();
File jsonDataInFile = new File("src/main/resources/Payloads/SimpleExecutionResult.json");
String url ="https://xray.cloud.getxray.app/api/v2/import/execution?testExecKey=XX-XX";
RequestSpecification request = RestAssured.given();
request.header("Content-Type", "application/json");
request.header("Authorization", "Bearer "+tokenResult.substring(1,(tokenResult.length()-1)));
request.body(jsonDataInFile);
Response response = request.post(url);
ResponseBody body = response.getBody();
System.out.println(body.asString());
}
auth.json
{
"client_id": "XXXXXXXXXXXXXXXXXX",
"client_secret": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
}
SimpleExecutionResult.json
{
"testExecutionKey": "XX-XX",
"tests": [
{
"testKey": "XX-XX",
"status": "FAILED"
},
{
"testKey": "XX-XX",
"status": "PASSED"
}
]
}

How to pass form-urlencoded data in GET request with SWIFT 5

I'm using Swift 5 and attempting to get an access token from an API I'm developing using asp.net MVC. With Postman I set my request to GET, pass in some information in the body, and I get back an access token.
In XCode when I try this it gives me the error: "GET method must not have a body."
My Code:
func GetToken(email: String, password: String) {
let dataToSend = [
"grant_type": "password",
"username": email,
"password": password
]
let newData = try! JSONSerialization.data(withJSONObject: dataToSend, options: [])
var request = URLRequest(url: getNewTokenURL)
request.httpMethod = "Get"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = newData
URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let data = data else {return}
do {
let myData = try JSONDecoder().decode(TokenResponse.self, from: data)
self.userToken = myData.accessToken
}
catch {
}
}.resume()
}
How do I perform the GET request with the data I need to send to it?
GET requests don't have a body. Parameters in a GET request are passed along with it's url as query parameters.
let url = URL(string: "https://www.example.com/getExample?sampleParam=sampleValue&anotherParam=anotherValue")
Edit: Also you need to give method in all caps. Since GET is the default you didn't have an issue.
Also if you are sure that the data is being passed as JSON then the method should be a POST method for that you just need to set the method of the request to POST as follows:
request.method = "POST"
Note: It's case sensitive.

Flutter Dio post an object with array

I am trying to post a request to api with an object as"
var params = {
"item": "itemx",
"options": [1,2,3],
};
print(params);
try {
Response response = await _dio.post(getAddToCartURL,
queryParameters: params,
options: Options(headers: {
HttpHeaders.contentTypeHeader: "application/json",
}));
} catch (error, stackTrace) {
print("Exception occurred: $error stackTrace: $stackTrace");
return false;
}
Dio sends the object as :
POST /api/add-to-cart/?item=itemx&options%5B%5D=1&options%5B%5D=2&options%5B%5D=3
in which the api recognize it as a bad request.
what is wrong that i am doing here? I have even tried the list as [ "1","2","3"], it is the same.
It all depends on how the API expects it. I would suggest trying to encode it as JSON.
var params = {
"item": "itemx",
"options": jsonEncode([1,2,3]),
};
But sending complex data in query parameters isn't always that easy. Since you are using POST anyway, maybe send a JSON object as body instead of using query parameters.
var params = {
"item": "itemx",
"options": [1,2,3],
};
...
Response response = await _dio.post(getAddToCartURL,
options: Options(headers: {
HttpHeaders.contentTypeHeader: "application/json",
}),
data: jsonEncode(params),
);
another example for any one might be helpful , posting fomr data
var formData = FormData.fromMap({
'data': json.encode(
{'salt': salt, 'placeholder': 'palceholder',
'method_name': 'app_details'})
});
var response = await dio.post(
BaseUrl,
data: formData,
);
the final result of your request is this

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"
}
}

Resources