Is directions Api not accepting negative values for coordinates ? Flutter - json

I'm sending a direction request to an API and I'm facing this problem.
With coordinates as flutter: start location is :latitude 37.33101308, longitude -122.03065487 and end location is :latitude 37.33097983, longitude -122.03063943 the - symbol creates a problem.
When sending the resulting request
http://www.yournavigation.org/api/1.0/gosmore.php?format=geojson&v=bicycle&fast=0&layer=mapnik&flat=37.33101308&flon=-122.03065487&tlat=37.33097983&tlon=-122.03063943&geometry=1&instructions=1&lang=it
I get an error that I'm not yet able to understand:
[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception:
FormatException: Unexpected character (at character 1) ^
0 _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1394:5)
1 _ChunkedJsonParser.parseNumber (dart:convert-patch/convert_patch.dart:1261:9)
2 _ChunkedJsonParser.parse (dart:convert-patch/convert_patch.dart:926:22)
3 _parseJson (dart:convert-patch/convert_patch.dart:31:10)
4 JsonDecoder.convert (dart:convert/json.dart:495:36)
5 JsonCodec.decode (dart:convert/json.dart:153:41)
6 jsonDecode (dart:convert/json.dart:96:10)
7 DirectionsRepository.postRequest (package:fixit_cloud_biking/directions/directions_repository.dart:39:26)
8 DirectionsBloc.getDirections (package:fixit_cloud_biking/directions/directions_bloc.dart:46:12)
9 _AsyncStarStreamController.runBody (dart:async-patch/async_patch.dart:155:5)
10 _rootRun (dart:async/zone.dart:1122:3<…>
Is it because of a json formatting issue or does it means that www.yournavigation.org/api doesn't accept negative coordinates values ?
This error doesn't happen if the sent request has positive coordinates as this
'http://www.yournavigation.org/api/1.0/gosmore.php?format=geojson&v=bicycle&fast=0&layer=mapnik&flat=44.5018645003438&flon=11.340018709036542&tlat=44.502138&tlon=11.340402&geometry=1&instructions=1&lang=it'
Just for testing I tried just making them positive coordinates with .abs(). but of course the results is a wrong location on the map.
Is there another coordinate system that has all positive values?
Thank you very much for your help.
This is the class I'm sending the request from:
import 'package:http/http.dart';
import 'package:latlong/latlong.dart';
import 'dart:convert' as convert;
import 'dart:math';
class DirectionsRepository {
Future<List<LatLng>> postRequest(LatLng start, LatLng end) async {
print('postRequest() called');
print(
'start location is :latitude ${start.latitude}, longitude ${start.longitude}');
print(
'end location is :latitude ${end.latitude}, longitude ${end.longitude}');
// NORMAL NEGATIVE LONGITUDE THROWS = API ERROR:
// format error [VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: FormatException: Unexpected character (at character 1)
String flat = (start.latitude).toString();
String flon = (start.longitude).toString();
String tlat = (end.latitude).toString();
String tlon = (end.longitude).toString();
// ALL POSITIVE VALUES DON'T THROW AN ERROR BUT IS WRONG PLACE
// String flat = (start.latitude).abs().toString();
// String flon = (start.longitude).abs().toString();
// String tlat = (end.latitude).abs().toString();
// String tlon = (end.longitude).abs().toString();
final request =
'http://www.yournavigation.org/api/1.0/gosmore.php?format=geojson&v=bicycle&fast=0&layer=mapnik&flat=$flat&flon=$flon&tlat=$tlat&tlon=$tlon&geometry=1&instructions=1&lang=it';
print('final request is $request');
// working properly
// final request =
// 'http://www.yournavigation.org/api/1.0/gosmore.php?format=geojson&v=bicycle&fast=0&layer=mapnik&flat=44.5018645003438&flon=11.340018709036542&tlat=44.502138&tlon=11.340402&geometry=1&instructions=1&lang=it';
// Await the http get response, then decode the json-formatted response.
var response = await get(request);
if (response.statusCode == 200) {
var jsonResponse = convert.jsonDecode(response.body);
print('${jsonResponse.runtimeType} : $jsonResponse');
List<dynamic> coordinates = jsonResponse['coordinates'];
print('coordinates are : $coordinates');
print('coordinates are: ${coordinates.length}');
Map<String, dynamic> properties = jsonResponse['properties'];
// print('properties are $properties');
String distance = properties['distance'];
print('Route is $distance Km long.');
String instructions = properties['description'];
print('instructions are $instructions');
List<LatLng> suggestedRoute = [];
for (int i = 0; i < (coordinates.length); i++) {
dynamic coordinate = coordinates[i];
LatLng position = LatLng(coordinate[1], coordinate[0]);
suggestedRoute.add(position);
print('position is $position');
print(i);
}
print('postRequest() suggestedRoute is $suggestedRoute');
return suggestedRoute;
} else {
print(
'postRequest() Request failed with status: ${response.statusCode}.');
}
}
}

After a few tries, I've nailed down the problem to be a direction API server problem. So, request is fine, but method's json decoding just fails because gets a 242 response status code which passes the check but fails as the response body does not match what's handled in the method.

Related

Dart FormatException: Unexpected character (at character 1) in empty json

Basically what the title says, simply trying to implement a condition that either writes to a an existing file or decodes the json and then writes to the same file.
code:
import 'dart:io';
import 'dart:convert';
import 'ToDo.dart';
void main() async{
print("hello");
int prio1;
print("Title:");
String? title1 = stdin.readLineSync();
print("description:");
String? des = stdin.readLineSync();
ToDo test = new ToDo(title1, des, 0, false);
String test11 = jsonEncode(test);
print(test11);
final filename = 'vault.json';
if(File(filename).length == 0)
{
new File(filename).writeAsString("["+test11+"]");
}
else{
String test = await jsonDecode(filename);
String test2 = test.substring(0, test.length - 1);
String test3 = ","+test2 +"]";
new File(filename).writeAsString(test3);
}
}
my json file "vault.json" is empty, yet I get this error:
Unhandled exception:
FormatException: Unexpected character (at character 1)
vault.json
^
#0 _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1405:5)
#1 _ChunkedJsonParser.parseNumber (dart:convert-patch/convert_patch.dart:1272:9)
#2 _ChunkedJsonParser.parse (dart:convert-patch/convert_patch.dart:937:22)
#3 _parseJson (dart:convert-patch/convert_patch.dart:40:10)
#4 JsonDecoder.convert (dart:convert/json.dart:612:36)
#5 JsonCodec.decode (dart:convert/json.dart:216:41)
#6 jsonDecode (dart:convert/json.dart:155:10)
#7 main (file:///D:/Code/dart/json/json.dart:23:27)
#8 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:19)
#9 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
any help appreciated!
edit:added ToDo.dart in case you want to run the program
class ToDo {
String? title,description;
int prio;
bool completed;
ToDo(this.title, this.description, this.prio, this.completed);
ToDo.fromJson(Map<String,dynamic> json):
title = json['title'],
description = json['description'],
prio = json['prio'],
completed = json['completed'];
Map<String,dynamic> toJson() => {
'title':title,
'description':description,
'prio':prio,
'completed':completed,
};
}
I am not exactly sure what you want to achieve but this snippets lets you read and write into that json file.
Please notice that we have to read the json from the file first with readAsLinesSync before decoding. This caused your error, since you didn't try to decode the json object (for example [{"title":"test","description":"test","prio":0,"completed":false}] but just the file name (vault.json), which of course isn't a valid json.
import 'dart:io';
import 'dart:convert';
import 'ToDo.dart';
void main() async{
const filename = 'vault.json';
print('Enter title');
String? title = stdin.readLineSync();
print('Enter description');
String? description = stdin.readLineSync();
final file = File(filename);
final fileIsEmpty = await file.length() == 0;
if(fileIsEmpty)
{
// create a test ToDO
ToDo testToDo = ToDo(title, description, 0, false);
String test11 = jsonEncode(testToDo);
// write to File
await File(filename).writeAsString(test11);
}
else {
// read the ToDO from the file
final json = File(filename).readAsLinesSync();
final encode = jsonDecode(json.first);
ToDo storedToDo = ToDo.fromJson(encode);
print(storedToDo);
}
}
Also consider using snake case for your file names, which is best practice.
Happy coding!

Parse JSON in websocket sharp

I'm trying to parse JSON string that received from websocket sharp but keep failing.
using (var ws = new WebSocket(WebAddr))
{
ws.Log.Level = LogLevel.Debug;
ws.OnOpen += (ss, ee) =>
{
System.IO.File.WriteAllText(#"C:\log.txt", "connected!");
};
ws.OnMessage += (ss, ee) =>
{
JsonValue jo = JsonValue.Parse(ee.Data);
string value = (string)jo["levelid"];
Console.Write(value + '\n');
};
}
It just threw exception error when reaches string value... part.
I'm using System.Json from nuget.
I think I figured it out. The server will respond with 2 messages, one is Json object and one is Json array.
dynamic jo = JsonConvert.DeserializeObject(ee.Data);
This fixed my problem!

How to send a POST with a JSON in a WebRequest() call using MQL4?

I would like to send a POST from MQL4-script, using a JSON-format to a Node-server.
I've tried the webRequest() standard function in MQL4, based on the following documentation, but it did NOT success.
From MQL4 Documentation:
Sending simple requests of type "key=value" using the header `Content-Type: application/x-www-form-urlencoded`.
int WebRequest( const string method, // HTTP method
const string url, // URL
const string cookie, // cookie
const string referer, // referer
int timeout, // timeout
const char &data[], // the array of the HTTP message body
int data_size, // data[] array size in bytes
char &result[], // an array containing server response data
string &result_headers // headers of server response
);
and
Sending a request of any type specifying the custom set of headers for a more flexible interaction with various Web services.
int WebRequest( const string method, // HTTP method
const string url, // URL
const string headers, // headers
int timeout, // timeout
const char &data[], // the array of the HTTP message body
char &result[], // an array containing server response data
string &result_headers // headers of server response
);
Parameters
method [in] HTTP method.
url [in] URL.
headers [in] Request headers of type "key: value", separated by a line break "\r\n".
cookie [in] Cookie value.
referer [in] Value of the Referer header of the HTTP request.
timeout [in] Timeout in milliseconds.
data[] [in] Data array of the HTTP message body.
data_size [in] Size of the data[] array.
result[] [out] An array containing server response data.
result_headers [out] Server response headers.
Returned value:
HTTP server response code or -1 for an error.
Does anyone know how to perfom it?
UPDATE:
Here is the code on the MQL4-script side :
#include <Json\hash.mqh>
#include <Json\KoulJSONMgmt.mqh>
void OnStart()
{
string strParam = StringConcatenate("{","\"currency\"",":","\"",Symbol(),"\"",",","\"timeframe\"",":","\"",IntegerToString(Period()),"\"",",","\"ticktime\"",":","\"",TimeToString(TimeLocal(),TIME_DATE|TIME_SECONDS),"\"",",","\"bid\"",":",DoubleToString(MarketInfo(Symbol(),MODE_BID),4),",","\"ask\"",":",DoubleToString(MarketInfo(Symbol(),MODE_ASK),4),",","\"spread\"",":",DoubleToString(MarketInfo(Symbol(),MODE_SPREAD),0),"}");
JSONParser *parser = new JSONParser();
JSONValue *jv = parser.parse(strParam);
string strJson = jv.toString();
if (jv == NULL) {
Print("error:"+(string)parser.getErrorCode()+parser.getErrorMessage());
} else {
Print("PARSED:"+strJson);
//Example of json String :
//EURUSD,M15: PARSED:{"bid" : 1.1152,"ask" : 1.1154,"spread" : 13,"ticktime" : "2016.10.10 16:24:01","currency" : "EURUSD","timeframe" : "15"}
}
string cookie=NULL,headers;
char post[],result[];
int res;
string strResult,result_header;
headers = "application/json";
prmUrl=StringConcatenate("http://localhost/api"+"/"+"ticks");
//--- Reset the last error code
ResetLastError();
int timeout=1000; //--- Timeout below 1000 (1 sec.) is not enough for slow Internet connection
int intHostNameLength=StringLen(prmParameter);
StringToCharArray(prmParameter,post,0,intHostNameLength);
res=WebRequest("POST",prmUrl,headers,timeout,post,result,result_header);
//--- Checking errors
if(res==-1)
{
Print("Error in WebRequest. Error code =",GetLastError());
//--- Perhaps the URL is not listed, display a message about the necessity to add the address
Print("Add the address '"+prmUrl+"' in the list of allowed URLs on tab 'Expert Advisors'","Error",MB_ICONINFORMATION);
}
else
{
for(int i=0;i<ArraySize(result);i++)
{
if( (result[i] == 10) || (result[i] == 13)) {
continue;
} else {
strResult += CharToStr(result[i]);
}
}
ArrayCopy(strResult,result,0,0,WHOLE_ARRAY);
}
Print(strResult);
}
And the Node side is :
server.js
//Create new Tick
app.post('/api/ticks', function(req, res) {
console.log('Inserting New Tick');
var tick = req.body;
console.log('>'+JSON.stringify(tick,null,4));
Tick.addTick(tick, function(err, tick){
if(err) res.json(err);
res.json(tick);
});
});
and in model ticks.js
var mongoose = require('mongoose');
// User Schema
var TickSchema = mongoose.Schema({
currency:{
type: String
},
timeframe: {
type: String
},
ticktime: {
type: Date
},
bid: {
type: Number
},
ask: {
type: Number
},
spread: {
type: Number
},
createddate :{
type: Date,
default: Date.now
}
}, {collection : 'fxTicks'});
var Tick = module.exports = mongoose.model('Tick', TickSchema);
//Create New Tick
module.exports.addTick = function(tick, callback){
Tick.create(tick, callback);
};
// Get Ticks
module.exports.getTicks = function(callback, limit){
Tick.find(callback).limit(limit);
};
So, back to the square No.1:
In the last-year's post, there was a step by step methodology to proceed with a MCVE-based approach to the problem isolation.
Repeating the same steps here, inside MQL4-code,
adding a python-based mock-up WebSERVER, to diagnose the actual working client/server http-protocol exchange & handshaking, ( not the WebSERVER-side interpretation of the delivered POST-request, which is the same, as if one have launched the URL from a WebBROWSER, for all related details ref: BaseHTTPServer.BaseHTTPRequestHandler )
>>> import BaseHTTPServer
>>> server_class = BaseHTTPServer.HTTPServer
>>> handler_class = BaseHTTPServer.BaseHTTPRequestHandler
>>> httpd = server_class( ( '', 8765 ), handler_class )
>>> httpd.handle_request()
127.0.0.1 - - [10/Oct/2016 09:46:45] code 501, message Unsupported method ('GET')
127.0.0.1 - - [10/Oct/2016 09:46:45] "GET /?test=123_from_Chrome HTTP/1.1" 501 -
>>> httpd.handle_request()
127.0.0.1 - - [10/Oct/2016 09:47:23] code 501, message Unsupported method ('GET')
127.0.0.1 - - [10/Oct/2016 09:47:23] "GET /favicon.ico HTTP/1.1" 501 -
>>>
>>>
>>>
>>> httpd = server_class( ( '', 80 ), handler_class )
>>> httpd.handle_request()
127.0.0.1 - - [10/Oct/2016 10:22:05] code 501, message Unsupported method ('GET')
127.0.0.1 - - [10/Oct/2016 10:22:05] "GET /?test=123_from_Chrome_on_port_80 HTTP/1.1" 501 -
>>> httpd.handle_request()
127.0.0.1 - - [10/Oct/2016 10:22:31] code 501, message Unsupported method ('GET')
127.0.0.1 - - [10/Oct/2016 10:22:31] "GET /?test=123_from_Chrome_on_port_80_again HTTP/1.1" 501 -
>>> httpd.handle_request()
127.0.0.1 - - [10/Oct/2016 10:22:34] code 501, message Unsupported method ('GET')
127.0.0.1 - - [10/Oct/2016 10:22:34] "GET /favicon.ico HTTP/1.1" 501 -
>>> httpd.handle_request()
127.0.0.1 - - [10/Oct/2016 11:25:56] code 501, message Unsupported method ('GET')
127.0.0.1 - - [10/Oct/2016 11:26:12] "GET /?test=123_from_Chrome_on_port_80_another_call HTTP/1.1" 501 -
>>>
>>>
127.0.0.1 - - [10/Oct/2016 12:03:03] code 501, message Unsupported method ('POST')
127.0.0.1 - - [10/Oct/2016 12:03:03] "POST / HTTP/1.1" 501 -
>>>
the output isproviding an evidence that the last pair of rows were produced by an MQL4-side WebRequest() that was setup correctly and works fine there and back[ MetaTrader Terminal 4 ]-Log reads:
2016.10.10 12:03:03.921 ___StackOverflow_WebRequest_DEMO XAUUSD,H1:
DATA:: <head><title>Error response</title></head>
<body>
<h1>Error response</h1><p>Error code 501.<p>
Message: Unsupported method ('POST').<p>
Error code explanation: 501 = Server does not support this operation.
</body>
2016.10.10 12:03:03.921 ___StackOverflow_WebRequest_DEMO XAUUSD,H1:
HDRs:: HTTP/1.0 501 Unsupported method ('POST')
Server: BaseHTTP/0.3 Python/2.7.6
Date: Mon, 10 Oct 2016 20:03:03 GMT
Content-Type: text/html
Connection: close
A raw MQL4-snippet BUT use at one's own risk! ( strongly encourage NOT to use any BLOCKING WebRequest() callsin any Production-grade code...for NON-BLOCKING tools see my other posts and how to or read into internal details on high-performance, low-latency, non-blocking integration tools for distributed heterogeneous systems processing alike ZeroMQ or nanomsg )
All have been warned, so:
Last years setup picture is still valid:
The mock-up WebSERVER had inside the dotted form-field input of:
http://localhost/
One shall also bear in mind, that trying to set a specific port designation in the URL will violate the MetaQuotes Inc. design rule, that a port is being derived from the protocol pragma at the beginning of the URL declaration, so:
http://localhost:8765/
will not work, as MQL4 WebRequest() CANNOT use other port but either of { 80 | 443 }, given by protocol pragma stated in URL: { http: | https: }
Thus for any port-numbering gymnastics, one has to setup and tune a proper set of port-forwarding services, that would leave MetaTrader Terminal 4 live inside this design-cage, using just either of { 80 | 443 }.
The simplest MQL4-script OnStart() demonstrator looks this way:
//+------------------------------------------------------------------+
//| ___StackOverflow_WebRequest_DEMO.mq4 |
//| Copyright © 1987-2016 [MS] |
//| nowhere.no |
//+------------------------------------------------------------------+ >>> https://stackoverflow.com/questions/39954177/how-to-send-a-post-with-a-json-in-a-webrequest-call-using-mql4
#property copyright "Copyright © 1987-2016 [MS]"
#property link "nowhere.no"
#property version "1.00"
#property strict
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart(){
/* A BRIGHTER WAY:
string JSON_string = StringFormat( "{\"currency\": \"%s\", \"timeframe\": \"%d\", \"ticktime\": \"%s\", \"bid\": %f, \"ask\": %f, \"spread\": %s }", _Symbol,
Period(),
TimeToString( TimeLocal(), TIME_DATE | TIME_SECONDS ),
MarketInfo( _Symbol, MODE_BID ),
MarketInfo( _Symbol, MODE_ASK ),
MarketInfo( _Symbol, MODE_SPREAD )
);
// A SMARTER WAY & THE FASTEST PROCESSING TIMES:
// --------------
#define MQL4_COMPILE_TIME_JSON_TEMPLATE "{\"currency\": \"%s\", \"timeframe\": \"%d\", \"ticktime\": \"%s\", \"bid\": %f, \"ask\": %f, \"spread\": %s }" // CONSTANT TEMPLATE TO FILL-IN AD-HOC VALUES:
// +
string JSON_string = StringFormat( MQL4_COMPILE_TIME_JSON_TEMPLATE", _Symbol,
Period(),
TimeToString( TimeLocal(), TIME_DATE | TIME_SECONDS ),
MarketInfo( _Symbol, MODE_BID ),
MarketInfo( _Symbol, MODE_ASK ),
MarketInfo( _Symbol, MODE_SPREAD )
);
*/
string JSON_string = StringConcatenate( "{", // **** MQL4 can concat max 63 items
"\"currency\"",
":",
"\"",
Symbol(),
"\"",
",",
"\"timeframe\"",
":",
"\"",
IntegerToString( Period() ),
"\"",
",",
"\"ticktime\"",
":",
"\"",
TimeToString( TimeLocal(), TIME_DATE | TIME_SECONDS ),
"\"",
",",
"\"bid\"",
":",
DoubleToString( MarketInfo( Symbol(), MODE_BID ), 4 ),
",",
"\"ask\"",
":",
DoubleToString( MarketInfo( Symbol(), MODE_ASK ), 4 ),
",",
"\"spread\"",
":",
DoubleToString( MarketInfo( Symbol(), MODE_SPREAD ), 0 ),
"}"
);
// */
/* off-topic: a JSON-string VALIDATOR -----------------------------------------------------------------------------------------------------------------------------------
#include <Json\hash.mqh>
#include <Json\KoulJSONMgmt.mqh>
JSONParser *parser = new JSONParser();
JSONValue *jv = parser.parse(strParam);
string strJson = jv.toString();
if ( jv == NULL ) Print( "ERROR:" + (string) parser.getErrorCode()
+ parser.getErrorMessage()
);
else Print( "PARSED:" + strJson );
// Example of a journalled Print() for an above setup JSON String :
// EURUSD,M15: PARSED:{"bid" : 1.1152,"ask" : 1.1154,"spread" : 13,"ticktime" : "2016.10.10 16:24:01","currency" : "EURUSD","timeframe" : "15"}
*/ // off-topic: a JSON-string VALIDATOR -----------------------------------------------------------------------------------------------------------------------------------
// string ReqSERVER_URL = "http://localhost:8765/", // **** MQL4 WebRequest CANNOT use other port but either of { 80 | 443 } given by protocol pragma stated in URL: { http: | https: }
string ReqSERVER_URL = "http://localhost/", // ---- MQL4 WebRequst
ReqCOOKIE = NULL,
// ReqHEADERs = "application/json"; // **** MQL4 WebRequest MUST use [in] Request headers of type "key: value", separated by a line break "\r\n".
ReqHEADERs = "Content-Type: application/json\r\n";
int ReqTIMEOUT = 5000; // ---- MQL4 WebRequest SHALL use [in] Timeouts below 1000 (1 sec.) are not enough for slow Internet connection;
// ================================================= // ~~~~ MQL4 WebRequest SHALL be AVOIDED as an un-control-able BLOCKING-SHOW-STOPPER, any professional need shall use NON-BLOCKING tools
char POSTed_DATA[],
result_RECVed_DATA_FromSERVER[];
int result_RetCODE;
string result_DecodedFromSERVER,
result_RECVed_HDRs_FromSERVER;
// int intHostNameLength = StringLen( ReqSERVER_URL );
// StringToCharArray( ReqSERVER_URL, POSTed_DATA, 0, StringLen( ReqSERVER_URL ) );
// StringToCharArray( prmParameter, post, 0, intHostNameLength );
StringToCharArray( JSON_string, POSTed_DATA, 0, StringLen( JSON_string ) );
ResetLastError();
result_RetCODE = WebRequest( "POST",
ReqSERVER_URL,
ReqHEADERs,
ReqTIMEOUT,
POSTed_DATA,
result_RECVed_DATA_FromSERVER,
result_RECVed_HDRs_FromSERVER
);
if ( result_RetCODE == -1 ) Print( "Error in WebRequest. Error code =", GetLastError() ); // returns error 4060 – "Function is not allowed for call" unless permitted -- ref. Picture in >>> https://stackoverflow.com/questions/39954177/how-to-send-a-post-with-a-json-in-a-webrequest-call-using-mql4
else {
for ( int i = 0; i < ArraySize( result_RECVed_DATA_FromSERVER ); i++ ) {
if ( ( result_RECVed_DATA_FromSERVER[i] == 10 ) // == '\n' // <LF>
|| ( result_RECVed_DATA_FromSERVER[i] == 13 ) // == '\r' // <CR>
)
continue;
else result_DecodedFromSERVER += CharToStr( result_RECVed_DATA_FromSERVER[i] );
}
Print( "DATA:: ", result_DecodedFromSERVER );
Print( "HDRs:: ", result_RECVed_HDRs_FromSERVER );
}
}
//+------------------------------------------------------------------+
Deviations from documented steps are easily visible in the source and were left for clarity.
Epilogue:
If documentation says something, it is worth keeping that advice ( with some tests, sure ).
If a sponsored Community advice says something, it is worth giving it at least a try, before asking for more.
It works well for me, I have someone like this :
string response = SendResquest("POST", "GetPrediction", "[4, 7]", "Content-Type: application/json", 5000);
string SendResquest(string httpType, string methodName, string bodyData = "", string headers = "", int timeout)
{
uchar bodyDataCharArray[];
ArrayResize(bodyDataCharArray, StringToCharArray(bodyData, bodyDataCharArray)-1);
int response = WebRequest(httpType, this.address+methodName, headers, timeout, bodyDataCharArray, this.resultDataCharArray, this.resultHeader);
string result = CharArrayToString(this.resultDataCharArray);
if(response == 200)
return result;
Print("Error when trying to call API : ", response);
return "";
}
Allow your [ MetaTrader Terminal 4 ] to communicate with URL via menu:
Tools -> Options -> Expert Advisors ->
1. mark a check-box [ X ] in front of 'Allow WebReq....'
&
2. type the URL name below the check-box, using the green (+) icon, inside the form.
If this doesn't help - try to add Print() statements to see the possible errors ( incorrect MQL4 code or incorrect JSON-format file ).
Have you tried setting the headers like this:
headers = "Content-Type: application/json\r\n";
?

Unity3d Facebook Response Data parsing

I was able to solve this solution is in the coment
I have problem with parsing data that I get rom Facebook on appRequestCallback.
The request is send and that part is ok. But I need to pars the send data for the internal uses.
the code is this
private void appRequestCallback(FBResult result)
{
Util.Log("appRequestCallback");
if (result != null)
{
var responseObject = Json.Deserialize(result.Text) as Dictionary<string, object>;
object obj = 0;
string resp = (string)responseObject["request"];
Util.Log ("resp : " + resp);
if (responseObject.TryGetValue("cancelled", out obj))
{
Util.Log("Request cancelled");
}
else if (responseObject.TryGetValue("request", out obj))
{
responseObject.TryGetValue("to", out obj);
string[] s = (string[]) obj;
Util.Log ("s: " + s);
AddPopupMessage("Request Sent", ChallengeDisplayTime);
Util.Log("Request sent");
}
}
}
In the console I get this
appRequestCallback
UnityEngine.Debug:Log(Object)
resp: 870884436303337
UnityEngine.Debug:Log(Object)
And then the error
InvalidCastException: Cannot cast from source type to destination type.
MainMenu.appRequestCallback (.FBResult result) (at Assets/Resources/Scripts/MainMenu.cs:482)
Facebook.AsyncRequestDialogPost.CallbackWithErrorHandling (.FBResult result)
Facebook.AsyncRequestString+c__Iterator0.MoveNext ()
The problem is in parsing of to: part of json file and I am not sure why. I have tried to cast it into string, string[], List<>, Array, ArrayList. As I see the problem is that I am not using the good cast type for the to: but I can not figure out what the correct cast type is

Facing Issue with Timespan in rest service serialization

I am using REST service to get the data from the Db.
In my class, I am having the property "UploadTime" of datatype TimeSpan?.
The time span is calculated based on the difference between dates and in the response,I ma getting response as :
ArrayOfUploadUI xmlns="http://schemas.datacontract.org/2004/07/NMS.ApplicationService.HIM.Objects" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<UploadUI>
<UID>1</UID>
<DateCompleted>2015-01-08T10:46:25.25</DateCompleted>
<DateNotified>2015-01-07T10:46:25.25</DateNotified>
<DateDictationStartTime i:nil="true" />
<DateDictationEndTime i:nil="true" />
<UploadTime>P1D</UploadTime>
<ExistsOnBackend>false</ExistsOnBackend>
</UploadUI>
</ArrayOfUploadUI>
.
I am getting the following exception while trying to get the data:
using (HttpResponseMessage response = await _HttpClient(session).GetAsync(apiUrl))
{
if (response.IsSuccessStatusCode)
result = await response.Content.ReadAsAsync<T>();
else
await _HandleInvalidResponseAsync(response);
}
I am getting issue at the "response.Content.ReadAsAsync();".
Error is:
Error converting value "P1D" to type 'System.Nullable`1[System.TimeSpan]'. Path '[0].UploadTime', line 1, position 518.
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader reader, Object value, CultureInfo culture, JsonContract contract, Type targetType).
I googled and I came to know that WCF serilaizing the "timeSpan"datatype from "1:0:0:00" to "P1D".
My issue is how to deserialize this on the response level.
I have done formatting for the date at the source level and the issue got resolved.
JsonSerializerSettings dateFormatSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
};
string jsonNMSPlatformObject = JsonConvert.SerializeObject(nmsPlatformObject,dateFormatSettings);
using (HttpContent httpContent = new StringContent(jsonNMSPlatformObject))
{
httpContent.Headers.ContentType = new MediaTypeHeaderValue(JsonMedaType);
var request = new HttpRequestMessage(HttpMethod.Delete, apiUrl);
request.Content = httpContent;
using (HttpResponseMessage response = await _HttpClient(session).SendAsync(request))
{
if (response.IsSuccessStatusCode)
return;
else
await _HandleInvalidResponseAsync(response, jsonNMSPlatformObject);
}
}