-1

I am running a simple client code in C to do POST and GET to server and read data stream. Currently I am printing full response received in recv() and have to parse it for further use. Before reading data stream, I want to know what is HTTP status code (200, 400, 401 etc.) from server. I am getting same in Header. Is there a way to get HTTP code before reading Headers?

What is best practice to Read Head parameters and Payload? I searched but answers I got are to read '\r\n' sequence and than apply logic. Is there any better way?

I am using Ubuntu systems for testing this code. Following is response being printed:

<p style="color:blue;">HTTP/1.1 401 Unauthorized  
Server: Apache-Coyote/1.1  
Content-Type: application/json  
Content-Length: 69  
Date: Mon, 08 Aug 2016 09:46:46 GMT  
</p>
<p style="color:blue;">"You are not a authorized user to access this resource. Access denied."
Ilya
  • 4,583
  • 4
  • 26
  • 51
B Patel
  • 1
  • 1
  • 1
  • ' Is there a way to get HTTP code before reading Headers? ' already doesn't make sense. The HTTP status code is *in* a header. Unclear what you're asking, or why you're reimplementing client-side HTTP when there are already many working libraries available. To implement HTTP you need a good knowledge of TCP, sockets, and RFC 2616 and its successors. – user207421 Aug 08 '16 at 12:15

1 Answers1

0

No. recv() receives raw data from the socket, TCP/IP in this case I suppose. TCP/IP is a lower level protocol and does not have the notion of HTTP status code, the HTTP data is just bytes to it with no meaning.

So you really have to read the data, interpret it as HTTP protocol data, and then get the status code from it.


You should separate the concerns of TCP/IP and HTTP protocols. You can either write a simple HTTP client library yourself if you want to learn, or find an existing library (libcurl comes to mind) if you need production quality code. Then use the library to handle the HTTP protocol handling, and hide the lower level TCP/IP traffic from the application code.

hyde
  • 60,639
  • 21
  • 115
  • 176