I have the following code to send POST, but I am getting an error with that even it compile correctly
http_client client(U("http://l0.71.103.63:34568"));
json::value postData;
postData["name"] = json::value::string(U("Mohammad"));
http_response response = client.request(methods::POST,postData.to_string().c_str()).get();
if(response.status_code() == status_codes::OK)
{
auto body = response.extract_string();
std::wcout << L"Added new Id: " << body.get().c_str() << std::endl;
return std::stoi(body.get().c_str());
}
But I am getting the following error when try to run the program
terminate called after throwing an instance of 'web::uri_exception'
what(): provided uri is invalid: {"name":"Mohammad"}
Aborted (core dumped)
I think the problem is your IP address. It looks like your IP address is wrong? You have "http://l0." where the "10" is "l0" (lowercase L).
Hence the web:uri_exception.
You are wrong (I do think) in your request, should look like that:
auto response = client.request(methods::POST, U("\"), postData).get();
The second argument in the request is the URL complement, and you are passing your json in string, hence the error you have.
basically the syntax you want is this one:
pplx::task web::http::client::http_client::request (
const method & mtd, const utility::string_t &
path_query_fragment, const json::value & body_data, const
pplx::cancellation_token & token = pplx::cancellation_token::none()
)
Related
I have a C++ code that parses incoming json message using rapidjson.
The json message received contains one key:value pair ("userID": 100), where the value is an integer.
However, if the value is sent as a string '100', rapidjson crashed the whole program with the following error:
Invalid response: { "error": "ERR_RATE_LIMIT"}
trading: ../../include/rapidjson/document.h:1737: int rapidjson::GenericValue<Encoding, Allocator>::GetInt() const [with Encoding = rapidjson::UTF8<>; Allocator = rapidjson::MemoryPoolAllocator<>]: Assertion `data_.f.flags & kIntFlag' failed.
/home/ray/dev/trading_execution/src/trading/trading.run.sh: line 39: 2518 Aborted (core dumped) ./trading 1234
I would expect rapidjson can handle this more gently than crashing the program.
Any suggestion how to deal with this situation? For example, is there a better way to handle the error?
Json message:
{
"ctRequestId": "cfa5511f-8c1a-492b-b81a-1462d03bbe99",
"requestType": "generic",
"userID": 100,
}
Code:
userID = getJSONInt(document, "userID");
int getJSONInt(rapidjson::Document& document, const char* memberName)
{
int memberValue;
try
{
if (document.HasMember(memberName))
memberValue = document[memberName].GetInt();
}
catch(const std::exception& e)
{
std::cerr << e.what() << '\n';
}
return memberValue;
}
No expert of rapidjson, but according to the documentation (http://rapidjson.org/md_doc_tutorial.html)
Note that, RapidJSON does not automatically convert values between JSON types. If a value is a string, it is invalid to call GetInt(), for example. In debug mode it will fail an assertion. In release mode, the behavior is undefined.
In the following sections we discuss details about querying individual types.
If you look in the table in the section "Querying Number" of the linked document you can find some member function you can use to test the type before extracting it. In your case you might want to try IsInt()
Edit: for the particular use case IsUint/GetUint may be more appropriate as pointed out in the comments
Try this:
{
...,
...,
"UserId" : "100" // note double quotes for 100
}
And if the value of "UserId" is string, then query it using GetString() query and not GetInt() to pass assertion test.
I am trying to receive stream from some GRPC server, code of which is not accessible to me.
Here is the code of my GRPC client:
class Client():
def __init__ (self, grpcIP, grpcPort, params):
self.channel = grpc.insecure_channel('%s:%d' % (grpcIP, grpcPort))
grpc.channel_ready_future(self.channel).result()
self.stub = pb2_grpc.DataCloneStub(self.channel)
self.params = params
self.host = grpcIP
def StartSender(self):
params = pb2.StartParameters(**self.params)
try:
res = self.stub.Start(params)
print(type(res))
for pr in res:
print(pr.current_progress)
except grpc.RpcError as e:
print(e)
Here are snippets from proto file that is used.
Method:
rpc Start (StartParameters) returns (stream Progress) {}
Message in stream:
message Progress {
double current_progress = 1;
uint64 total_sent = 2;
uint64 total_size = 3;
string file_name = 4;
Error error = 5;
}
As I understand self.stub.Start(params) should return iterator with objects of type Progress. The problem is that it returns something with type grpc._channel._Rendezvous. I can`t iterate through the response. It doesn`t catch any exceptions either.
Did someone experience such behavior? Is it possible that issue comes not from client side?
Class grpc._channel._Rendezvous is also an iterator, you can check the streaming RPC example here.
The code you posted is correct implementation. If the program blocked at the for pr in res line, it is possible that the server is not sending any response (or taking a long time), hence the client side is blocked.
I want to create following json request:
{
"Value1":{},
"Value2":"some string value"
}
to achieve this I have tried following code in cpp:
json::value &refRequest
json::value jRequest = json::value();
refRequest[requestKey::Value1] = json::value(json::value::object()); //for creating empty object
refRequest[requestKey::Value2] = json::value::string("some string");
but it gives output as:
{
"Value1":},
"Value2":"some string value"
}
if you observe, instead of returning empty object as {} it gives the output as } and this results in to malformed request. I am not sure where exactly I am going wrong, any help will would be appreciated. Thanks
I believe your mistake is that you are constructing a json::value from a json::value::object()
According to the documentation the line should be fixed to:
refRequest[requestKey::Value1] = json::value::object();
We are receiving this callback using ExitGames Photon Realtime engine when an event is fired
customEventAction(int playerNr,
nByte eventCode,
const ExitGames::Common::Object& eventContent)
If the object is a string we use this code to extract it
ExitGames::Common::JString str =
ExitGames::Common::ValueObject<ExitGames::Common::JString>(eventContent).getDataCopy();
However, the object being sent is a dictionary. It's being sent from the server using BroadcastEvent.
How do we get data out of it ?
We've tried this, but it doesn't make any sense:
ExitGames::Common::Dictionary<byte,ExitGames::Common::Object> pdic
= ExitGames::Common::ValueObject<ExitGames::Common::Dictionary<byte,ExitGames::Common::Object>>(eventContent).getDataCopy();
I've found code to get the data from a hashtable, but that doesn't work either.
thanks
Shaun
ExitGames::Common::Dictionary<nByte, ExitGames::Common::Object> dic = ExitGames::Common::ValueObject<ExitGames::Common::Dictionary<nByte, ExitGames::Common::Object> >(eventContent).getDataCopy();
is absolutely correct and works for me.
The cause of your problem must be inside another line.
When you replace the implementations of sendEvent() and customEventAction() in demo_loadBalancing inside one of the Photon C++ client SDKs with the following snippets, then that demo successfully sends and receives a Dictionary:
send:
void NetworkLogic::sendEvent(void)
{
ExitGames::Common::ValueObject<ExitGames::Common::JString> obj(L"test");
ExitGames::Common::Dictionary<nByte, ExitGames::Common::Object> dic;
dic.put(1, obj);
mLoadBalancingClient.opRaiseEvent(false, dic, 0);
}
receive:
void NetworkLogic::customEventAction(int /*playerNr*/, nByte /*eventCode*/, const ExitGames::Common::Object& eventContent)
{
EGLOG(ExitGames::Common::DebugLevel::ALL, L"");
ExitGames::Common::Dictionary<nByte, ExitGames::Common::Object> dic = ExitGames::Common::ValueObject<ExitGames::Common::Dictionary<nByte, ExitGames::Common::Object> >(eventContent).getDataCopy();
const ExitGames::Common::Object* pObj = dic.getValue(1);
ExitGames::Common::JString str = ExitGames::Common::ValueObject<ExitGames::Common::JString>(pObj).getDataCopy();
mpOutputListener->write(L"received the following string as Dictionary value: " + str);
}
This gives me the following line of output on the receiving client:
received the following string as Dictionary value: test
I have a REST API that returns a string with files metadata. Among those files I have one that has "" (0xEF0xBF0xBF, link) character in name. When I try to parse such a response I get exception that says:
e = {_message="* Line 1, Column 13 Syntax error: Malformed string literal" }
This is the string I'm trying to parse:
{"files":[["Thunderbolt Gigabit Ethernet Adapter.txt",["bc288518-c426-4dbd-9600-a213a35d1c04",1447772221866,9,"Bartosz","Siewior"]],["System.Windows.Interactivity.dll",["56ce759b-019b-4723-8fca-7af877908971",1440507238241,55904,"Bartosz","Siewior"]]],"folderPermission":[["MODIFY"]],"directories":[]}
The code I'm using to receive and parse the string:
// ...
client.request(request).then([&](web::http::http_response response) {
status_code = response.status_code();
//response.extract_json(true).then([&](pplx::task<web::json::value> previousTask) {
response.extract_string().then([&](pplx::task<utility::string_t> previousTask) {
try {
utility::string_t str_response = previousTask.get();
web::json::value root;
root = web::json::value::parse(str_response);
}
catch (const web::http::http_exception& e) {
std::wstringstream ss;
ss << e.what();
str_response = ss.str();
}
catch (const web::json::json_exception& e) {
std::wstringstream ss;
ss << e.what();
str_response = ss.str();
}
TaskExecutionData data = { task.id, status_code, str_response.c_str() };
callback(data);
}).wait();
}).wait();
VS2013 JSON Visualizer can parse and show the result properly: VS_json_visualizer
I've tried C++REST version 2.5.0 and 2.6.0, neither of them is able to parse that string... Do you have any ides?
Answer from Casablanca's team:
The issue is that on windows we parse using UTF16 and the particular character you're having issues with maps to 0xFFFF. This is also the character returned by std::char_traits::eof(), so we detect the code point as an "end of stream" signal and terminate the parse appropriately.
The UTF8 parser should not have these issues, so as a workaround you can probably do something similar to how the current web::json::value::parse() function works in json_parsing.cpp:1245, except using char as the template parameter instead of utility::char_t.