Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
So this question has been asked before, but the general answer pointed to was using an external library such as cURLpp. So I was curious as to if HTTP requests could be done using only the standard libraries as of C++14. How difficult would this be?
Say for example, I wanted to get an XML document and store it in a string to be parsed. What steps would have to be taken to achieve this?
If anyone is curious, I'm doing this as a learning experience to better understand how HTTP requests work.
It sounds like to me that you want to implement the HTTP protocol from scratch on top of the POSIX sockets API. I have done this myself, it was quite fun.
Read about the sockets API here: http://en.wikipedia.org/wiki/Berkeley_sockets
If you want to work on Windows, see here.
This link, posted in the comments, provides a pretty good starting-point example for using the API, although it weirdly includes both the client and the server as serial logic within the same program -- which may allow it to bypass some of the calls (such as waiting for incoming connections) required to implement a client or server as a standalone program.
Assuming you are implementing an HTTP server in C++, you might choose to implement the client as a web page (running on your favorite browser), as the following hack demonstrates...
<html>
<head>
</head>
<body>
This web page sends the entered text back to the server upon a button press.
The server's response is then displayed in the box below.
This is only a hack for learning purposes, and not a demonstration of best-practices.
<br>
<textarea id="INP">
Hello world!
</textarea>
<br>
<button onclick="return make_request('INP','GET','test1')">GET Request</button>
<button onclick="return make_request('INP','POST','test2')">POST Request</button>
<div id="result" style='border-style:solid;'>?</div>
<script>
function make_request( textID, request_type, webfn )
{
var url = "" + "?webfn="+webfn // assumes this page was served by the same server
if ( request_type != 'POST' ) url += "&value="+document.getElementById(textID).value;
var req = new XMLHttpRequest();
req.open( request_type, url, /*async*/false );
req.send( request_type=='POST' ? document.getElementById(textID).value : null );
if ( req.readyState == 4/*complete*/ && req.status == 200/*OK*/ )
{
result = req.responseXML.documentElement.getElementsByTagName('value')[0].firstChild.data;
document.getElementById('result').innerHTML = req.responseText;
}
else alert("HTTP request failed");
return false;
}
</script>
</body>
</html>
Related
I'm in charge to a build a react-native chatbot app, that must help users to signup during the discussion.
The chat must start with a greeting message and few quick-replies, in which we find a "Sign me up" option. When the user presses that option, the bot asks hem to write an email address in order to start the process.
I've made a little project based on the example available on react-native-gifted-chat repository.
Please use this link to get to my code: https://github.com/firas1220/react-native-chatbot
I'd appreciate if someone gives some hand or maybe we can add improvements and transform the repo into something original 😉.
This question might help some people facing similar situations.
As an attachment, a demo in GIF image.
Just add an InputText (https://reactnative.dev/docs/textinput) and then to ref.current.focus()
Something like this:
const inputRef = useRef();
const onAction = () => {
inputRef.current.focus();
}
<InputText ref={inputRef} value=... />
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
How do i read data as text from a BLOB Url in WebView2 ? I've tried WebView2 callback from Javascript which i couldn't make it work. I appreciate whether it is a Javascript solution or not but i prefer C++.
WebView2 doesn't provide a mechanism to interact with Blobs. You can turn the Blob into text in script and then post the text back to the native side with the window.chrome.webview.postMessage method and the WebMessageReceived event.
If this doesn't work for you, you can make a feature request on the WebView2 Feedback GitHub Project.
async function example() {
function textToBlob(text) {
return new Blob([text], {type : 'text/plain'});
}
async function blobToText(blob) {
return (new Response(blob)).text();
}
const blob = textToBlob("example");
const text = await blobToText(blob);
alert(text);
}
example();
Unfortunately, Webview2 doesn't support async function results in ExecuteScript. I managed to get data by performing synchronous request with ajax.
wstring jquery(L"var jqry = document.createElement('script');"
L"jqry.src = 'https://code.jquery.com/jquery-3.3.1.min.js';"
L"document.getElementsByTagName('head')[0].appendChild(jqry);");
webview->ExecuteScript(jquery.c_str(), Callback<ICoreWebView2ExecuteScriptCompletedHandler>(
[](HRESULT errorCode, PCWSTR result) -> HRESULT {
return S_OK;
}).Get());
Sleep(500);
wstring script(L"jQuery.noConflict();"
L"function testAjax() {"
L"var result='';"
L"jQuery.ajax({"
L"url:document.getElementById('test').href,"
L"async: false,"
L"success:function(data) {"
L"result = data; "
L"}"
L"});"
L"return result;"
L"}"
L"(() => {"
L"return testAjax()"
L"})();");
webview->ExecuteScript(script.c_str(), Callback<ICoreWebView2ExecuteScriptCompletedHandler>(
[](HRESULT errorCode, LPCWSTR result) -> HRESULT {
wprintf(L"%ls\n", result);
return S_OK;
}).Get());
But synchronous calls block the web code while executing. This is not recommended, but it is ok for my case. If you are looking for another way without blocking the web code, posting the text back to the native side maybe a better idea as #David Risney suggested.
I'm using the QT WebEngine framework to display web pages. I'm injecting javascript into a page when it loads, and want to allow the javascript to be able to access a QT object. Apparently, to do this a QWebChannel must exist that establishes some IPC between chromium (the javascript) and the rest of my C++/QT project. I came across the QWebEnginePage::setWebChannel (QWebChannel *channel) function, however I can't find any examples of its use. The documentation (http://doc.qt.io/qt-5/qwebenginepage.html#setWebChannel) mentions that qt.webChannelTransport should be available in the javascript context, but I don't see where that is established in qwebchannel.js (https://github.com/qtproject/qtwebchannel/blob/dev/src/webchannel/qwebchannel.js). I've seen the WebChannel examples (http://doc.qt.io/qt-5/qtwebchannel-examples.html) and would like to avoid WebSockets if possible.
Below is how I tried to implement the web channel.
Whenever a page loads I establish a channel and inject the javascript in C++:
QWebChannel *channel = new QWebChannel();
channel->registerObject(QStringLiteral("jshelper"), helper);
view->page()->runJavaScript(qwebjs); //this is qwebchannel.js
view->page()->setWebChannel(channel);
view->page()->runJavaScript(myfunction); //function that calls QT object (jshelper)
In Javascript:
new QWebChannel(qt.webChannelTransport, function(channel) { ... });
Which results in the channel not being connected properly (assuming this is because of qt.webChannelTransport, as it was working when I was using WebSockets). Any pointers to examples of QWebChannel being set up with QWebEnginePage this way is also appreciated.
Short answer: add <script type="text/javascript" src="qrc:///qtwebchannel/qwebchannel.js"></script> to your html page (before you call new QWebChannel of course), and remove the line view->page()->runJavaScript(qwebjs); //this is qwebchannel.js from your C++ code.
Long answer:
I too had a ton of trouble figuring out how to use QWebChannel without WebSockets correctly -- managed to get it working after digging around in Qt 5.5 source code and mailing lists (documentation is still lacking). Note that this only works with the new Qt 5.5.
Here's how to use QWebChannel:
// file: MyWebEngineView.cpp, MyWebEngineView extends QWebEngineView
QWebChannel *channel = new QWebChannel(page());
// set the web channel to be used by the page
// see http://doc.qt.io/qt-5/qwebenginepage.html#setWebChannel
page()->setWebChannel(channel);
// register QObjects to be exposed to JavaScript
channel->registerObject(QStringLiteral("jshelper"), helper);
// now you can call page()->runJavaScript(...) etc
// you DON'T need to call runJavaScript with qwebchannel.js, see the html file below
// load your page
load(url);
And on the JS side:
<!-- NOTE: this is what you're missing -->
<script type="text/javascript" src="qrc:///qtwebchannel/qwebchannel.js"></script>
<script type="text/javascript">
<!-- it's a good idea to initialize webchannel after DOM ready, if your code is going to manipulate the DOM -->
document.addEventListener("DOMContentLoaded", function () {
new QWebChannel(qt.webChannelTransport, function (channel) {
var jshelper = channel.objects.jshelper;
// do what you gotta do
});
});
</script>
Also make sure you've added QT += webenginewidgets webchannel to your .pro file else this won't build!
Bonus: you can debug your JavaScript from the comfort of Chrome Dev Tools now! Just add this somewhere in your Qt code (ideally in your application startup):
#ifdef QT_DEBUG
qputenv("QTWEBENGINE_REMOTE_DEBUGGING", "23654");
#endif
Then start your application, navigate to http://localhost:23654 in Chrome, and you'll get a fully-functional JS debugger, profiler, console, etc :)
Follow-up (19/04/2016): if your remote debugger isn't working, note that the qputenv call must also occur before any calls to QWebEngineSettings or any other WebEngine-related class, because these trigger the WebEngine "zygote" process immediately (the zygote is the parent QtWebEngineProcess from which all future QtWebEngineProcesses are forked) and then qputenv cannot affect it. Spent a few hours tracking this down.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am on project right now which is a very simple parental control software, but, I want to know what is the url requested in firefox to take respond based on it ... if you may help because I don't know how to let my software know what is the url requested by firefox .. How to do that?
I have to use C++ in most of my software.. but if there are better language to do this task please advice me
In Firefox you need to use XPCOM component called nsIHTTPChannel. This script below will block abort all rqeuests to google. The channel is opened but aborted before opening connection to server.
var {classes: Cc, results: Cr, utils: Cu} = Components;
Cu.import('resource://gre/modules/Services.jsm');
var httpRequestObserver =
{
observe: function(subject, topic, data)
{
var httpChannel, requestURL;
if (topic == 'http-on-modify-request') {
httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);
requestURL = httpChannel.URI.spec;
if (/google\.com/.test(requestURL)) {
httpChanel.cancel(Cr.NS_BINDING_ABORTED);
}
return;
}
}
};
Services.obs.addObserver(httpRequestObserver, 'http-on-modify-request', false);
//Services.obs.removeObserver(httpRequestObserver, "http-on-modify-request", false); //run this to remove observer
Can I suggest an alternative approach? Instead of writing an extension for Firefox and an extension for Chrome and an extension for IE... listen on the OS network interfaces for traffic and block undesirable URLS.
This is traditionally the job of a firewall. Using an existing solution will provide the most efficient means of solving your problem. I'm not familiar with the capabilities of the built in Windows firewall or 3rd party alternatives but something like this would be trivial with iptables (Linux).
I notice that Growl allows for the possibility of Growl notifications from a website. Has anyone tried implementing this?
If so, what form did it take? Did you implement multi user support? And, can you provide any code examples (C# or Objective-C would preferable but I'm not that fussed)?
Rich
There are GNTP (Growl Network Transport Protocol) bindings for various languages, a list of bindings can be found here - these allow you to send notifications from, say, a PHP script.
I wouldn't trust Growl's UDP system directly, but rather write a server that receives and stores notifications (maybe as a tiny web app), and a local script that routinely grabs any new messages via HTTP and Growls them. Not complicated at all, will be more reliable than UDP, and can queue up messages when your Growl'ing machine is powered-off or unreachable. Shouldn't take long to implement
Basically, server.php in pseudo-PHP (which could use Net_Growl):
<?php
if($_GET['action'] == "store"){
$title = $_POST['title'];
$message = $_POST['message'];
$password = sha1($_POST['password']);
if($password == "..."){
store_in_database(sanitise($title), sanitise($message);
}
} else {
print(json_encode(get_notifications_from_database()));
mark_notifications_as_read();
}
?>
client.py in pseudo-Python (which could use gntp):
while 1:
time.sleep(60):
data = urllib.urlopen("http://myserver.com/server.php?action=get&password=blah").read()
for line in data:
notif = json.decode(line)
growl.alert(notif['title'], notif['message'])