I am writing a mobile application for Android on Delphi 10. My program sends a post and get requests using the THTTPClient component. The script on the server accepts requests in the format, so when sending a request, you must specify in the header "Content Type: application / json". The fact is that I can't change the Content Type. When you send a Get request, it will change, but when you send a Post request, it will not. I use about this code:

procedure ThomeForm.Button1Click(Sender: TObject); var data: TStringList; H: THTTPClient; begin data := TStringList.Create; data.Add('{"phone":"' + HomeForm.Phone.Text + '"}'); h := THTTPClient.Create; h.ContentType := 'application/json'; h.Accept := 'application/json, text/plain, */*'; log.Text := h.Post('https://site.ru/api/phone', data).ContentAsString(); end; 

Why does this happen and how to fix it?

  • one
    and if through CustomHeaders to enter? Between "accepts json requests" and "it is necessary to specify the" link " therefore " is not very correct. In general, there is usually no such duty, but the server as a whole can filter requests by this header. - teran
  • Used CustomHeaders - did not help, the result is the same. The server filters requests, and therefore you need to specify "Content Type: application / json" in the header. - Artem Zolotarevsky

1 answer 1

HttpClient has 4 Post overload methods:

 // Post a raw file without multipart info function Post( const AURL: string; const ASourceFile: string; const AResponseContent: TStream = nil; const AHeaders: TNetHeaders = nil ): IHTTPResponse; overload; // Post TStrings values adding multipart info function Post( const AURL: string; const ASource: TStrings; const AResponseContent: TStream = nil; const AEncoding: TEncoding = nil; const AHeaders: TNetHeaders = nil ): IHTTPResponse; overload; // Post a stream without multipart info function Post( const AURL: string; const ASource: TStream; const AResponseContent: TStream = nil; const AHeaders: TNetHeaders = nil ): IHTTPResponse; overload; // Post a multipart form data object function Post( const AURL: string; const ASource: TMultipartFormData; const AResponseContent: TStream = nil; const AHeaders: TNetHeaders = nil ): IHTTPResponse; overload; 

The first and third methods send data as is, the second method (which you used) sends data as application/x-www-form-urlencoded , the fourth method sends data as multipart/form-data .

Thus, you need to use the first or third method if you want to send raw data with your Content-Type .

An example using the third method:

 var data: TStringStream; H: THTTPClient; begin data := TStringStream.Create; try data.WriteString('{"phone":"' + HomeForm.Phone.Text + '"}'); h := THTTPClient.Create; try h.ContentType := 'application/json'; h.Accept := 'application/json, text/plain, */*'; log.Text := h.Post('https://site.ru/api/phone', data).ContentAsString(); finally h.Free; end; finally data.Free; end; end;