Monday, November 17, 2014

Send data through HTTP request BODY and URI

We know that every HTTP request/response has two sections. Head and body. The head section contains information, which represents the information about current http request. The body section contains data in general.
There are two ways to send data to server using HTTP request. One is through url which will carry in head section or through Body which will encode data in string format and embed it in http body section.

Generally, when we perform Get HTTP request to server, the client agent attach data through uri and thus pass data to server through header section.

However, when we make HTTP Post request, the client agent encode data and attach it in body section of request. As the data passes through body section, it is not visible to end user.

It does not mean that the data or HTTP request is very much secure. Because when data is encoded, it encodes in plain string format and easily anyone can decode it. The solution is to use HTTPS protocol.

Now, it’s not necessary to pass data from uri or request body depending on nature of request. I mean, we can send data through url even it is Post request. We will test it on ASP.NET MVC framework using Fiddler as client agent.

Pass data through URI

Here we will pass data through URI even it is Post type HTTP request. Here is sample code

   public class DummyController : ApiController
    {
       public void Post([FromUri] Object data)
       {
          
       }
       
    }

We are seeing that the data will come as object format and “FromUri” attribute has specified before parameter.


Once we hot on to Action , we will see that the data has came in parameter.


Now, how we will make sure that data has pass through URI not Body ? If we open the http request in Inspectors tab in fiddler, we will see the transformed URI and data is getting pass as query string.


Now, we will try to pass data through body of HTTP request.  For that we have to make little change in code. Here is modified code. Just we have change the “FromUri” attribute to “FromBody” attribute.

public class DummyController : ApiController
    {
       public void Post([FromBody] Object data)
       {
          
       }
       
    }

And if we generate one http Post request by specifying data in http body ,we will see that the data has embedded in body section of http request.


So, the conclusion is, there is complete freedom to choose way to send data in http request irrespective of method type.


1 comment:

  1. Sending data through an HTTP request body is a common method for transmitting information between a client and a server. Does Streaming Improve This allows for more extensive and structured data to be sent compared to query parameters.

    ReplyDelete