重定向到包含内容的其他网址

时间:2017-04-04 19:31:11

标签: c# php

我的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);

2 个答案:

答案 0 :(得分:0)

您可以在PHP中使用位置标头重定向到另一个页面:

<?php
  header("Location: http://www.somesite.com/another_page.php");
  exit();
?>  

无论来电者程序是C#还是其他语言。

答案 1 :(得分:0)

您需要在PHP端使用类似cURL的内容,以便在返回结果之前处理结果。

以下是使用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配置,某些安装没有安装/启用cURL模块。