Actionscript 3 Air iOS POST data not sending with URLLoader - ios

I have the following code to send POST data to my server:
var headers:Array = [
new URLRequestHeader("api_access_token", ACCESS_TOKEN),
new URLRequestHeader("api_secret", SECRET),
new URLRequestHeader("Content-type", "application/json")
];
var base_url = "http://example.com/";
var complete_func:Function;
function postRequest(url:String, params:Object, response_func:Function){
complete_func = response_func;
var request = new URLRequest(base_url+url);
request.requestHeaders = headers;
request.method = URLRequestMethod.POST;
request.contentType = "application/json";
request.data = JSON.stringify(params);
// Handlers
var postLoader = new URLLoader();
postLoader.addEventListener(Event.COMPLETE, parseResponse);
postLoader.addEventListener(IOErrorEvent.IO_ERROR, function(e:IOErrorEvent){ trace(e); });
postLoader.load(request);
}
function parseResponse(e:Event){
var data = e.target.data;
trace(data);
var json_data = JSON.parse(data);
complete_func(json_data);
}
Problem is, on my server, when I use var_dump($_POST) nothing but an empty array is returned. I don't know why this is the case. I have done traces on params and url parameters which contain relavent data.
The params I am sending are:
var customerDetails:Object = new Object();
customerDetails.first_name = firstNameField.text;
customerDetails.last_name = lastNameField.text;
customerDetails.dob = dobField.text;
customerDetails.email = emailField.text;
The headers retrieved by PHP's list_headers() returns:
array(6) { [0]=> string(24) "X-Powered-By: PHP/5.4.30" [1]=> string(38) "Expires: Thu, 19 Nov 1981 08:52:00 GMT" [2]=> string(77) "Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0" [3]=> string(16) "Pragma: no-cache" [4]=> string(44) "api_secret: example_secret" [5]=> string(50) "api_access_token: example_access" }
I am using Air 16.0 for iOS with ActionScript 3
Any help would be great. I don't know if this is a cross-domain policy issue.
P.S. Works fine with a GET request.

Use the right dataFormat:
loader.dataFormat = URLLoaderDataFormat.VARIABLES

As3 code is valid. You need improve from server side php code.. Please try this ..
<?php
$body = #file_get_contents('php://input');
$jsn = json_decode($body);
echo $jsn->first_name;
echo $jsn->last_name;
echo $jsn->dob;
echo $jsn->email;
?>

Related

C# reading OData $batch multipart/mixed response to a meaningful object(s)

I am consuming an OData Service, I am successfully POSTing my request (using RestSharp) to /$batch endpoint and getting the response. the response header contains
"Content-Type" : "multipart/mixed; boundary=<GUID>"
Body is
--C4254E82B51CFE5BD04201606B9AB7C50
Content-Type: multipart/mixed; boundary=C4254E82B51CFE5BD04201606B9AB7C51
Content-Length: 2221
--C4254E82B51CFE5BD04201606B9AB7C51
Content-Type: application/http; charset=utf-8
Content-Length: 2037
content-transfer-encoding: binary
HTTP/1.1 201 Created
Content-Type: application/json
Content-Length: 1732
location: https://test.api/Event/CarEntries('4003581738')
dataserviceversion: 2.0
etag: W/"datetimeoffset'2021-04-21T00%3A49%3A45Z'"
{ JSON }
--C4254E82B51CFE5BD04201606B9AB7C51--
--C4254E82B51CFE5BD04201606B9AB7C50
Content-Type: application/http; charset=utf-8
Content-Length: 15116
content-transfer-encoding: binary
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 15017
dataserviceversion: 2.0
{ JSON }
--C4254E82B51CFE5BD04201606B9AB7C50--
How do I deserialise and extract the JSON Objects in my C# code? I do not want to invent a Regex pattern (well that is my last resort)
I did try using "Simple.OData.Client" (also a few others) but my request is not 100% compatible with the "Simple.OData.Client".
Also tried extracting using the below code but not necessary give me what I want
var sc = new StringContent(response.Content);
var content = sc.ReadAsStreamAsync().Result;
var streamContent = new StreamContent(content);
streamContent.Headers.ContentType = MediaTypeHeaderValue.Parse(response.ContentType);
var provider = streamContent.ReadAsMultipartAsync().Result;
Can someone giveme the best way to extract the Json objects ?
Thanks
Nero
I manage to get this working HttpClient and System.Net.Http.Formatting.Extension
Below is the code
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://service-url/Entity/v1.3/$batch"))
{
request.Headers.TryAddWithoutValidation("Accept", "application/json");
request.Headers.TryAddWithoutValidation("Client-Id", "XXXXXXXXX");
// Add all the headers here
// this is your custom batch request
request.Content = new StringContent("--batch\ncontent-type: multipart/mixed;boundary=changeset\n\n--changeset\ncontent-type: application/http\nContent-Transfer-Encoding: binary\n\nPOST CarEntries HTTP/1.1\ncontent-type: application/json;charset=utf-8\naccept: application/json;\n\n{\n\"RefId\": \"Test\",\n\"Child\": {\n\"ChildId\": \"412000415\"\n}\n}\n--changeset--\n--batch--");
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/mixed;boundary=batch"); // This is imporatnt - but please refer to your api documentation
var response = await httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
var multiPartContent = await response.Content.ReadAsMultipartAsync(); // This is part of the extension
var mixedContent = multiPartContent.Contents.First(); // you will have multiple contents, select the content you want
var data = await mixedContent.ReadAsStringAsync();// read it as string
Regex rg = new Regex(#"\{(.|\s)*\}"); // find the json object from mixed content
var json = rg.Match(data);
return JsonConvert.DeserializeObject<TMessage>(json.Value);
}
}
Hope this helps someone in the future. But still, my goal is to use "Simple.OData.Client" or "Microsoft.OData.Client"

C# WebClient.UploadData in Rails

I have a c# method that I'm trying to convert to ruby on rails . I'm using unirest but I think something is not working correctly. This is my C# method :
private static string HTTPPoster(string url, string prmSendData)
{
try
{
WebClient wUpload = new WebClient();
wUpload.Proxy = null;
Byte[] bPostArray = Encoding.UTF8.GetBytes(prmSendData);
Byte[] bResponse = wUpload.UploadData(url, "POST", bPostArray);
Char[] sReturnChars = Encoding.UTF8.GetChars(bResponse);
string sWebPage = new string(sReturnChars);
return sWebPage;
}
catch
{
return "-1";
}
}
And This is what I tried so far in rails with unirest :
def HTTPPoster(url)
xml = "My XML Goes Here"
byte_array = xml.bytes
headers = {}
headers['Content-Type'] = "application/json"
headers['Accept'] = "application/json"
response = Unirest.post(url,
headers: headers,
parameters: {
body: byte_array
})
puts "response #{response.body}"
if ![200,201].include?(response.code)
raise "Mblox Error: #{response.code}, #{response.body}"
end
end
If you also know other libraries that can achieve what I need please let me know.
I used Faraday gem and sent the data as xml and not as byte array. And now I am achieving want I wanted.
response = Faraday.post(url) do |req|
req.headers['Content-Type'] = "application/xml"
req.headers['Accept'] = "*/*"
req.headers['Accept-Encoding'] = "gzip, deflate, br"
req.body = xml
end

Drawing directions from google map api

I am trying to draw a direction line from marker to another. I already turned on directions in google map api. I got this function in here (SO). I understand what its doing but I can not get it to work. The routes array returns empty. I have tried multiple points for tests. Here is the functions:
func drawPath2(origin: CLLocationCoordinate2D, destination: CLLocationCoordinate2D)
{
let origin = "\(origin.latitude),\(origin.longitude)"
let destination = "\(destination.latitude),\(destination.longitude)"
let apiKey = "Xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
guard let url = URL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=\(origin)&destination=\(destination)&key=AIzaSyAOhiBw8mSPBmmAJQ_fjM79x7ruvMxFmxQ") else {return}
Alamofire.request(url).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
let json = try! JSON(data: response.data!)
let routes = json["routes"].arrayValue
//remove this after test
print(routes.count)
for route in routes
{
let routeOverviewPolyline = route["overview_polyline"].dictionary
let points = routeOverviewPolyline?["points"]?.stringValue
let path = GMSMutablePath.init(fromEncodedPath: points!)
let polyline = GMSPolyline.init(path: path)
polyline.map = self.mapView
}
}
}
Here is the print() results:
Optional(https://maps.googleapis.com/maps/api/directions/json?origin=49.18705,-123.107261&destination=49.1844,-123.1052&mode=driving&key=AIzaSyAOhiBw8mSPBmmAJQ_fjM79x7ruvMxFmxQ)
Optional(<NSHTTPURLResponse: 0x6000024c5ba0> { URL: https://maps.googleapis.com/maps/api/directions/json?origin=49.18705,-123.107261&destination=49.1844,-123.1052&mode=driving&key=AIzaSyAOhiBw8mSPBmmAJQ_fjM79x7ruvMxFmxQ } { Status Code: 200, Headers {
"Cache-Control" = (
"no-cache, must-revalidate"
);
"Content-Encoding" = (
gzip
);
"Content-Length" = (
130
);
"Content-Type" = (
"application/json; charset=UTF-8"
);
Date = (
"Mon, 10 Dec 2018 22:28:52 GMT"
);
Expires = (
"Fri, 01 Jan 1990 00:00:00 GMT"
);
Pragma = (
"no-cache"
);
Server = (
mafe
);
Vary = (
"Accept-Language"
);
"alt-svc" = (
"quic=\":443\"; ma=2592000; v=\"44,43,39,35\""
);
"x-frame-options" = (
SAMEORIGIN
);
"x-xss-protection" = (
"1; mode=block"
);
} })
Optional(129 bytes)
SUCCESS
0
I do not see data in there at all. I think something is wrong with URL or request. Please help me sirs and madams.
I suspect, your api key is not authorized to use this service. You can verify by printing json
print(json)
You should see this in response where the routes array is empty,
{
"error_message" = "This API project is not authorized to use this API.";
routes = (
);
status = "REQUEST_DENIED";
}
Go to Google cloud console and create a new project and enable Direction API. API Libary
And Place your API Key in your url
See this Link It helps you for sample API and Response for Google Direction API.

How do I can iterate cookie values from http response?

I am using rest API in my flutter app. For further request I need JSESSIONID which I received from my profile API. I successful got response but I need guide to iterate cookie value.
I followed following steps:
final response = await http.get(
strURL,
headers: {
"Authorization": basicAuth,
"Content-Type": "application/json"
},
);
String rawCookie = response.headers['set-cookie'];
print('rawCookie $rawCookie');
As print raw cookie it is printing details:
flutter: rawCookie __cfduid=d5bbe3f8a131478a78ae996e636cca0401544177738; expires=Sat, 07-Dec-19 10:15:38 GMT; path=/; domain=.rayz.ch; HttpOnly,JSESSIONID=6AD6698C5BFC90F1D089696A955E6824; Path=/; HttpOnly
I can iterate it by substring but I want to iterate it with a proper way. So please guide me on this.
With package:http you need to split the cookie string yourself using String.split. If you want to use the underlying http client, that gives you a pre-parsed list of cookies, for example:
HttpClient _httpClient = new HttpClient();
HttpClientRequest request = await _httpClient.postUrl(Uri.parse(url));
request.headers.set('content-type', 'application/json');
request.add(utf8.encode(json.encode(jsonMap)));
HttpClientResponse response = await request.close();
print(response.cookies); // this is a List<Cookie>
Here is my code which runs perfectly and if any key does not have value, then it shows range error. But as your doubt, this code is running fine.
var headersList = response.headers['set-cookie']!.split(";");
for(var kvPair in headersList){
var kv = kvPair.split("=");
var key = kv[0];
var value = kv[1];
if(key.contains("session_id")){
print(value);
}
}

UCWA 2.0 Trying to add forward contact but getting ParameterValidationFailure

I am using UCWA 2.0 for some Skype4Business integration in our intranet web application.
I can successfully connect and do some stuff for example: changing availability status or asking for callforwarding settings of the user.
What I like to do that does not work is set a forward contact for the user.
Documentation for this: click here
My code for the POST call:
using (var client = new HttpClient())
{
var param = new { target = "sip:user#domain.be" };
var paramJson = JsonConvert.SerializeObject(param, Formatting.Indented);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Referrer = new Uri(result4._links.xframe.href);
client.DefaultRequestHeaders.Add("Authorization", $"{result3.token_type} {result3.access_token}");
var url = $"https://ucwebext.domain.be/{applicationUrl}/me/callForwardingSettings/immediateForwardSettings/immediateForwardToContact";
var responseNew = await client.PostAsync(url, new StringContent(paramJson, Encoding.UTF8, "application/json"));
var responseString = await responseNew.Content.ReadAsStringAsync();
}
Same code using RestSharp:
var client = new RestClient($"https://ucwebext.domain.be/{applicationUrl}");
var restR = new RestRequest("/me/callForwardingSettings/immediateForwardSettings/immediateForwardToContact", Method.POST);
var param = new { target = "sip:user#domain.be" };
var jsonToSend = JsonConvert.SerializeObject(param, Formatting.Indented);
restR.AddParameter("application/json; charset=utf-8", jsonToSend, ParameterType.RequestBody);
restR.AddParameter("referer", result4._links.xframe.href);
restR.AddHeader("Authorization", $"{result3.token_type} {result3.access_token}");
restR.RequestFormat = DataFormat.Json;
var response = client.ExecuteAsPost(restR, "POST");
Request header from the call:
POST https://ucwebext.domain.be/ucwa/oauth/v1/applications/101024253230/me/callForwardingSettings/immediateForwardSettings/immediateForwardToContact HTTP/1.1
Accept: application/json
Referer: https://ucwebext.domain.be/Autodiscover/XFrame/XFrame.html
Authorization: Bearer cwt=AAEBHAEFAAAAAAAF...0Q_OXzsR4g4F-PpYaMGK10Pg
Content-Type: application/json; charset=utf-8
Host: ucwebext.domain.be
Content-Length: 48
Expect: 100-continue
{"target":"sip:user#domain.be"}
I get the following error:
{"code":"BadRequest","subcode":"ParameterValidationFailure","message":"Please check what you entered and try again.","parameters":[{"name":"target","reason":"MissingOrInvalid"}]}
I tried everything and don't understand why the parameter is not submitting or invalid.
Any help is much appreciated!
SOLUTION
Instead of using JSON I added the parameter as querystring which worked!
var client = new RestClient($"https://ucwebext.domain.be/{applicationUrl}");
var restR = new RestRequest($"/me/callForwardingSettings/immediateForwardSettings/immediateForwardToContact{Url.Encode("?target=sip:user#domain.be")}", Method.POST);
restR.AddParameter("referer", result4._links.xframe.href);
restR.AddHeader("Authorization", $"{result3.token_type} {result3.access_token}");
var response = client.ExecuteAsPost(restR, "POST");

Resources