2017-04-04 148 views
0

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

http://php.net/manual/en/function.header.php – mkaatman

+0

为何不从一开始就致电其他网站? –

+0

由于'proxy.php'需要从其他网站获取响应,并在将其返回到我的C#代码之前进行更改。 – Darius

回答

0

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

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

无论主叫程序是C#或其他语言。

+0

这不起作用,因为它不会让我在返回到我的C#应用​​程序之前处理响应。 – Darius

+0

你测试过了吗? –

+0

'<?php header(“Location:http:// elsewhere”); 回声“永远不会看到这条线”; ?>' – Darius

0

您将需要在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配置,一些设施没有/安装卷曲模块启用的一个例子。

+0

这里是有一些很好的例子卷曲另一个http://stackoverflow.com/questions/9802788/call-a-rest-api-in-php SO问题 – MrZander

+0

请问我下达请求流中的内容(来自我的C#代码)包含在curl调用中?或者我必须在执行之前手动添加它? – Darius

+0

@Darius你将不得不手动添加它。这是一个全新的API调用,来自运行PHP脚本的服务器。 – MrZander

相关问题