如何使用TIdHTTPProxyServer重定向Post请求

时间:2012-06-05 07:17:17

标签: c++ delphi indy10 c++builder-xe2

目前我想使用Indy10 TIdHTTPProxyServer重定向特定的Post请求。我按照页面

http://embarcadero.newsgroups.archived.at/public.delphi.internet.winsock/200904/0904301714.html

并写了一个简单的样本如下。

oid __fastcall TForm3::MyProxyHTTPBeforeCommand(TIdHTTPProxyServerContext *AContext)
{

    if (AContext->Target == "http://example.com/need_redirect_url" ) {

        TIdIOHandler* io = AContext->Connection->IOHandler;

        io->WriteLn("HTTP/1.0 302 Moved Temporarily");
        io->WriteLn("Location:  http://exampledomain.com/target_url");
        io->WriteLn("Connection: close");    
    }
}

如果我将“http://sample.com/need_redirect_url”按到浏览器的URL栏中,它就有效。 但如果它是针对同一URL的XMLHttpRequest,则不返回任何内容(无论是Post还是Get)。

我不得不承认我对HTTP的运作方式并不熟悉。而且我也想知道是否有更好的方法来做我想做的事。

虽然我使用的是C ++ Builder XE2。 Delphi样本也很受欢迎,因为使用C ++

的indy组件的例子较少

2 个答案:

答案 0 :(得分:3)

您的代码没有写一个空行来终止您要发送的HTTP标头。在TIdHTTPProxyServer事件处理程序退出后,您还需要抛出异常以防止OnBeforeCommand导航到客户端请求的URL。

试试这个:

void __fastcall TForm3::MyProxyHTTPBeforeCommand(TIdHTTPProxyServerContext *AContext) 
{ 
    if (AContext->Target == "http://xxx.com/need_redirect_url" )
    { 
        TIdIOHandler* io = AContext->Connection->IOHandler; 

        io->WriteLn("HTTP/1.0 302 Moved Temporarily"); 
        io->WriteLn("Location: http://mydomain.com/target_url"); 
        io->WriteLn("Connection: close");     
        io->WriteLn("");     

        Abort();
    } 
} 

答案 1 :(得分:0)

这似乎是XMLHttpRequest跨域政策问题,因为example.com!= mydomain.com - 请参阅http://en.wikipedia.org/wiki/XMLHttpRequest#Cross-domain_requests了解背景信息和潜在解决方案

相关问题