我在使用Delphi与Indy客户端连接到公共域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组件的属性/设置?
发布于 2016-09-20 09:03:30
经过相当多的研究,我在印第知识库上找到了解决问题的方法。
http://www.indyproject.org/KB/iamgettinga403forbiddene.htm
我将indy组件的UserAgent属性从默认值更改为
Mozilla/3.0 (兼容;印第图书馆)
而且很管用!
https://stackoverflow.com/questions/39574291
复制相似问题