在使用Delphi 7和Indy发送Web服务请求时遇到问题。我的工作场所以公立医院为客户,以保险第三方为服务器。这是服务目录:
URL : {BASE URL from the insurance office}/Delete Method : DELETE Format : Json Content-Type: Application/x-www-form-urlencoded Request body : {"request": {"t_obj": {"noObj": "0301X1018V001","user": "myUser"}}}我使用Indy 10.6,我写的一些代码是:
Json := '{"request": {"t_obj": {"noObj": "0301X1018V001","user": "myUser"}}}';
req := TStringStream.Create(Utf8Encode(Json));
resp := TStringStream.Create('');
IdHttp1.request.Source := req;
IdHttp1.Request.ContentType := 'Application/x-www-form-urlencoded';
IdHttp1.delete('{BASE URL from the insurance office}/Delete', resp);
showmessage(resp.DataString);
但是,请求发送后,删除失败。 有人可以帮助我吗?对不起,我的英语还不够好。 谢谢。
答案 0 :(得分:0)
Application/x-www-form-urlencoded
不是用于发送JSON的有效媒体类型。您确定服务器实际上并不期望使用application/json
吗?应该是。
除此之外,您的请求不起作用的一个更重要的原因是因为TIdHTTP.Delete()
方法根本不允许发送帖子正文,因此服务器根本看不到JSON。在内部,Delete()
调用TIdCustomHTTP.DoRequest()
方法,并在nil
参数中传递ASource
,该方法将替换您对TIdHTTP.Request.Source
属性的分配。
要执行您要尝试的操作,您将必须直接致电DoRequest()
,例如:
// TIdCustomHTTP.DoRequest() is protected,
// so use an accessor class to reach it...
type
TIdHTTPAccess = class(TIdHTTP)
end;
...
Json := '{"request": {"t_obj": {"noObj": "0301X1018V001","user": "myUser"}}}';
req := TStringStream.Create(UTF8Encode(Json));
try
resp := TStringStream.Create('');
try
//IdHttp1.Request.Source := req;
//IdHttp1.Request.ContentType := 'Application/x-www-form-urlencoded';
IdHttp1.Request.ContentType := 'application/json';
//IdHttp1.Delete('{BASE URL from the insurance office}/Delete', resp);
TIdHTTPAccess(IdHttp1).DoRequest(Id_HTTPMethodDelete, '{BASE URL from the insurance office}/Delete', req, resp, []);
ShowMessage(resp.DataString);
finally
resp.Free;
end;
finally
req.Free;
end;