HTTP Requests in C++ without external libraries? [closed]

拟墨画扇 提交于 2021-02-08 08:16:07

问题


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.


回答1:


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>


来源:https://stackoverflow.com/questions/30228690/http-requests-in-c-without-external-libraries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!