How to encode HTTP POST parameters (C # client to a PHP server)?

I am having trouble finding the best way to encode POST parameters for a server call. I am writing a C # client that will be served by a PHP server. I want to allow more flexibility in the parameters, so my current plan is to have one parameter that I use for JSON encoding. For instance:

params = {"object":"Main","function":"doecho","params":["echothis...."]} 

I am using a C # WebRequest object and contentType for "application / x-www-form-urlencoded; charset = UTF-8". The data arrives at the server and everything works as expected until I add illegal JSON characters to the data.

For example, if I use the following data, then I can not do json_decode on it on the server side. It seems the server will automatically turn% 40 into a double quote (") when I read it with $ this-> getRequest () -> getParams (); (Zend_Framework).

 params = {"object":"Main","function":"doecho","params":["echothis%25%5d%22%40%3d%26...."]} 

What is the best practice here? Do I need to encode base64 data? Is there something obvious that I am missing a content type or php setting?

I have full control over the client and server, so I would like to know what to do correctly / better.

+6
source share
2 answers

Although a potential content type can be used to upload to HTTP, in practice three types are used:

  • One that is defined in this service documentation.
  • application / x-www-form-urlencoded - The default is HTML forms.
  • multipart / form-data is another form used by HTML formats, necessary when it includes form loading.

Due to the fact that 2 and 3 are used so often (since they are supported by the entire browser for submitting forms), almost all server technologies have everything for processing them. Therefore, if part of PHP does not do something strange, you can also use it.

application / x-www-form-urlencoded is not suitable for some data, but is the easiest for what it is used for. This is pretty much the same as how query strings are created for GET form requests, but as POST content.

Therefore, you want your content to be:

 "params=" + Uri.EscapeDataString(paramData) 

Thus, the first becomes:

 params=%7B%22object%22%3A%22Main%22%2C%22function%22%3A%22doecho%22%2C%22params%22%3A%5B%22echothis....%22%5D%7D 

And the second:

 params=%7B%22object%22%3A%22Ccmes_Main%22%2C%22function%22%3A%22doecho%22%2C%22params%22%3A%5B%22echothis%2525%255d%2522%2540%253d%2526....%22%5D%7D 

Both of the built-in PHP modules will return to the forms in your question.

+8
source

My first thought was to encode it as base64. I think this should be a simplified way.

From arcanecode.com :

 static public string EncodeTo64(string toEncode) { byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode); string returnValue = System.Convert.ToBase64String(toEncodeAsBytes); return returnValue; } 
+1
source

Source: https://habr.com/ru/post/900159/


All Articles