处理错误请求的自定义错误消息
我正在开发一个Android应用(客户端)。该服务器可与C#一起使用。当我特别提出一些请求时,我会在不良请求上收到一条错误消息,例如“未找到HTTP/1.1 404”,当我搜索的项目不正确时,这是可以的。但是在不良要求下,服务器也向我发送了JSON中的消息主体,类似的事情是:
{
"responseMessage":"The item you searched not found"
}
有没有办法获取此消息(而不是不好的请求消息'http/1.1 404找不到')并将其显示为错误的请求?后端正常工作,我在邮递员身上检查一下。我的邮政请求守则是:
Json := '{ '+
' "code":"'+str+'",'+
' "userid":'+userid+''+
' } ';
JsonToSend := TStringStream.Create(Json, TEncoding.UTF8);
try
IdHTTP1.Request.ContentType := 'application/json';
IdHTTP1.Request.CharSet := 'utf-8';
try
sResponse := IdHTTP1.Post('http://....', JsonToSend);
except
on e : Exception do
begin
ShowMessage(e.Message); // this message is : HTTP/1.1 404 Not Found
Exit;
end;
end;
finally
JsonToSend.Free;
end;
I'm developing an Android app (Client). The server works with C#. When I make some request specifically some Posts, I'm getting an error message on bad request such as 'HTTP/1.1 404 Not Found' which is okay when the item I searched for is incorrect. But on bad request the server sends me also a message body in JSON, something like this:
{
"responseMessage":"The item you searched not found"
}
Is there a way to get this message (and NOT the bad request message 'HTTP/1.1 404 Not Found') and show it as a response of bad request? The back end works fine, I check it on Postman. My code of Post request is this:
Json := '{ '+
' "code":"'+str+'",'+
' "userid":'+userid+''+
' } ';
JsonToSend := TStringStream.Create(Json, TEncoding.UTF8);
try
IdHTTP1.Request.ContentType := 'application/json';
IdHTTP1.Request.CharSet := 'utf-8';
try
sResponse := IdHTTP1.Post('http://....', JsonToSend);
except
on e : Exception do
begin
ShowMessage(e.Message); // this message is : HTTP/1.1 404 Not Found
Exit;
end;
end;
finally
JsonToSend.Free;
end;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要接收错误时的 JSON 内容,您有 2 个选项:
捕获引发的
EIdHTTPProtocolException
并从其ErrorMessage
属性读取 JSON,而不是Message< /代码>属性:
<前><代码>尝试
sResponse := IdHTTP1.Post(...);
除了
在 E: EIdHTTPProtocolException 上执行
开始
sResponse := E.ErrorMessage;
结尾;
on E: 例外
开始
ShowMessage(e.Message);
出口;
结尾;
结尾;
启用
hoNoProtocolErrorException
TIdHTTP.HTTPOptions
属性中的 code> 和hoWantProtocolErrorContent
标志,以防止引发TIdHTTP.Post()
HTTP 失败时发生EIdHTTPProtocolException
,而只是将 JSON 返回到sResponse
变量。如果需要,您可以使用TIdHTTP.ResponseCode
属性来检测 HTTP 失败:To receive the JSON content on errors, you have 2 options:
Catch the raised
EIdHTTPProtocolException
and read the JSON from itsErrorMessage
property, not theMessage
property:Enable the
hoNoProtocolErrorException
andhoWantProtocolErrorContent
flags in theTIdHTTP.HTTPOptions
property to preventTIdHTTP.Post()
from raisingEIdHTTPProtocolException
on HTTP failures, and instead just return the JSON to yoursResponse
variable. You can use theTIdHTTP.ResponseCode
property to detect HTTP failures, if needed: