重定向到包含内容的另一个网址
问题描述:
我的C#代码正在调用我的API服务(PHP),它需要将请求重定向到另一个url,并在返回之前处理响应。这里是我的C#代码:重定向到包含内容的另一个网址
HttpWebRequest request = null;
WebResponse response = null;
Stream writer = null;
request = (HttpWebRequest)WebRequest.Create(http://www.somewhere.com/proxy.php);
request.Method = "POST";
request.ContentType = "multipart/form-data; boundary=" + this.builder.Boundry;
this.builder.RequestStream.Position = 0;
byte[] tempBuffer = new byte[this.builder.RequestStream.Length];
this.builder.RequestStream.Read(tempBuffer, 0, tempBuffer.Length);
writer = await request.GetRequestStreamAsync().ConfigureAwait(false);
writer.Write(tempBuffer, 0, tempBuffer.Length);
writer = null;
response = await request.GetResponseAsync().ConfigureAwait(false);
然后在proxy.php
:
<?php
// 1. Redirect everything (with the content stream from the C# code) to http://www.elsewhere.com
// 2. Process the response from http://www.elsewhere.com
// 3. Return processed data to my C# code
?>
我怎样才能做到这一点?它需要我穿上这条线的请求流重定向:
writer = await request.GetRequestStreamAsync().ConfigureAwait(false);
writer.Write(tempBuffer, 0, tempBuffer.Length);
答
您将需要在PHP端使用类似cURL的东西,以便在返回结果之前处理结果。
下面是使用卷曲得到的数据
function getData(){
$curl = curl_init("http://thewebsite.com/api/whatever");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($curl);
curl_close($curl);
return $data;
}
这也取决于你的PHP配置,一些设施没有/安装卷曲模块启用的一个例子。
http://php.net/manual/en/function.header.php – mkaatman
为何不从一开始就致电其他网站? –
由于'proxy.php'需要从其他网站获取响应,并在将其返回到我的C#代码之前进行更改。 – Darius