2017-04-04 60 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

相關問題