【发布时间】:2017-01-27 05:01:32
【问题描述】:
我在使用 Delphi XE 通过 Indy Client 连接到公共域 api 时遇到问题。
我可以成功连接到我的本地主机 Web 服务器 api (apache),但是在共享主机上对远程服务器(公共域)的类似尝试给了我一个禁止的 403 错误。
我可以使用 cURL 成功访问相同的公共域 api。因此,我排除了共享托管服务器上的权限/防火墙的任何问题。
function CallService(ServiceID: string;payload:string): string;
var
JsonToSend: TStringStream;
ServerResponse,EndPointURL: string;
LastJSONArray: TStringList;
MyIndy : TIdHTTP;
begin
//Local connection WORKS :)
EndPointURL := 'http://localhost/api/index.php';
//Remote/Public Domain connection FAILS :(
EndPointURL := 'http://example.com/api/index.php';
LastJSONArray := TStringList.Create();
LastJSONArray.Values['service_id'] := ServiceID;
LastJSONArray.Values['payload'] := payload;
JsonToSend := TStringStream.Create(LastJSONArray.Text, TEncoding.UTF8);
MyIndy := TIdHTTP.Create;
try
try
MyIndy.Request.Accept := 'application/json';
MyIndy.Request.ContentType := 'application/json';
MyIndy.Request.ContentEncoding := 'utf-8';
ServerResponse := MyIndy.Post(EndPointURL, JsonToSend);
Result := ServerResponse;
except
on E: EIdHTTPProtocolException do
//status := http.ResponseText;
//code := E.ErrorCode;
if E.ErrorCode = 401 then ShowMessage('You are not authorised!')
else ShowMessage('Poor Connection '+E.Message);
on E: Exception do begin
//do something else
ShowMessage('Poor Connection - B');
end;
end;
finally
MyIndy.Free();
JsonToSend.Free();
LastJSONArray.Free();
end;
end;
在调用公共 api 之前我需要设置/调整 TIdHTTP Indy 组件的属性/设置吗?
【问题讨论】:
-
你的 cURL 代码是什么样的? 403 表示您无权访问该 URL,它可能需要您没有提供给
TIdHTTP的身份验证凭据。你给 cURL 了吗?顺便说一句,utf-8不是有效的Request.ContentEncoding值。如果有的话,您应该改用Request.Charset(您不需要为application/json指定字符集)。 -
嘿雷米。我发现问题出在组件的 UserAgent 属性上。好像被宿主屏蔽了。