发送 POST 请求以使用 PHP 更改和检索数据


Send POST request to change and retrieve data with PHP

我有这个任务,我必须向外部站点发送POST请求以更改和检索一些数据 PHP .这是它的工作原理:

首先我去这个网站。然后使用谷歌浏览器检查该网站,然后转到"网络"选项卡。打开此窗口时,我将Varmepumpe - luft til luftINGEN更改为LITENEnergi这个名字现在出现在Network tab中。

单击Energi后,我在标题下看到以下内容:

General
Request URL:http://energiportalen.no/Mal/MinBolig/Energi
Request Method:POST
Status Code:200 OK
Remote Address:xxx
Response Headers
Access-Control-Allow-Origin:*
Cache-Control:private
Connection:keep-alive
Content-Length:84445
Content-Type:text/html; charset=utf-8
Date:Thu, 18 Feb 2016 08:36:39 GMT
Server:Microsoft-IIS/7.5
Via:1.1 m00180A11BB28 (squid/3.3.5)
X-AspNet-Version:4.0.30319
X-AspNetMvc-Version:3.0
X-Cache:MISS from m00180A11BB28
X-Cache-Lookup:MISS from m00180A11BB28:3128
X-Powered-By:ASP.NET
Request Headers
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip, deflate
Accept-Language:nb-NO,nb;q=0.8,no;q=0.6,nn;q=0.4,en-US;q=0.2,en;q=0.2
Connection:keep-alive
Content-Length:2430
Content-Type:application/json; charset=UTF-8
Cookie:ASP.NET_SessionId=e5tg3z53vbxtynib0htcsevr; _ga=GA1.2.599505589.1454574895; _gat=1
Host:energiportalen.no
Origin:http://energiportalen.no
Referer:http://energiportalen.no/Energianalyse/MinBolig/?municipality=0111&area=187&yoc=1989&type=2
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36
X-Requested-With:XMLHttpRequest
Request Payload
Address: null
Area: 187
BNR: 0
Baths: 0
BuildingMaterial: 0
Bulb: 0
CellarIsCrawlSpace: false
CellarIsHeated: false
CellarIsIncluded: false
CellarIsToAir: false
CoordinateSystemCode: 0
CoordinateX: 41.1052127
CoordinateY: -74.0100643
DayReduction: false
Dishwasher: true
Divided: 0
DividedAsString: "Vertikaldelt"
Dryer: true
DurationBathsPerson: [4, 4, 4, 4, 4, 4]
EnergySaving: false
FNR: 0
FindOptimalInitiative: null
Floor: 0
FloorAsString: "Øverst"
FloorType: 1
FloorsAboveGround: 1
Freezers: 1
FridgeFreezers: 0
FullAddress: "Bolig i Hvaler"
GNR: 0
HasCellarFloor: true
HasRegisteredCellarFloors: false
HeatCapacity: 0
HeatDisribution: 0
HeatingSystem1: 0
HeatingSystem2: 0
HeatingSystem3: 0
HeatingSystem4: 0
HeatingSystem5: 0
HeatingSystem6: 0
HeatingSystem7: 0
HeatingSystem8: 0
HeatingSystem9: 0
HeatingSystem10: 0
HeatingSystem11: 0
HeatingSystem12: 0
HeatingSystem13: 0
HeatingSystem14: 0
HeatingSystem15: 0
HeatingSystem16: 0
HeatingSystem17: 0
HeatingSystem18: 0
HeatingSystem19: 0
HeatingSystem20: 0
HeatingSystem21: 0
HeatingSystem22: 0
HeatingSystem23: 0
HeatingSystem24: 0
HeatingSystem25: 0
HeatingSystemsText: null
HousingId: 0
HousingType: 2
HousingTypeAsString: "Enebolig"
Id: null
IlluminationSources: 20
InfiltrationCondition: 0
IsNewHousing: false
Letter: null
MissingAddress: true
MissingArea: false
MissingHousingType: false
MissingLocation: true
MissingMunicipality: false
MissingYearOfConstruction: false
MunicipalityName: "Hvaler"
MunicipalityNo: 111
NightReduction: false
NumHoursIllumination: 15
NumShowersPerPersonPerWeek: [6, 6, 6, 6, 6, 6]
PartHeatedArea: 0.86
Persons: 4
Placement: 0
PlacementAsString: "Ende"
PostalCode: "0000"
PostalName: ""
PresentWindowUverdi: null
PriceCoke: 0.5
PriceElectricity: 0.9
PriceGas: 1
PriceHeating: 0.8
PriceOil: 0.8
PricePellets: 0.65
PriceWood: 0.5
RatingColor: null
RatingScale: null
Refrigerators: 1
Roof: 2
RoofType: 0
RoofTypeAsString: "Ikke angitt"
SNR: 0
Street: null
StreetNumber: null
TemperatureInsideColdZone: 10
TemperatureInsideWarmZone: 21
Throughout: false
UpgradedSum: null
UpgradedSumUnit: 0
UpgradedWindowUverdi: null
Ventilation: 1
WallThickness: 0
WallType: 0
WallTypeAsString: "Ikke angitt"
WashingMachine: true
WindowChangedYear: 1989
WindowType: 0
WindowTypeAsString: "Ikke angitt"
YearOfConstruction: 1989
initiatives: ["1"]
  0: "1"

请求有效载荷下,有大量与能源相关的参数,用于计算房屋的节能和类似内容。您可以更改区域、更改建造年份、更改使用的供暖系统等。如何在 PHP 中使用 POST 请求更改这些参数,以便将它们发送以进行重新计算,以便我可以从外部站点以 JSON 形式检索"网络"下的"预览"选项卡中的信息?

下面是"预览"选项卡的示例:

CO2Emissions: "380"
energy: {,…}
energyConsumption: "2 881"
energyCost: "2 592"
energyCostAsString: "kr 2 592"
lifetimeCO2Emissions: "11 400"
lifetimeEnergyConsumption: "86 430"
lifetimeSavings: 77760
liftetimeEnergyCostAsString: "kr 77 760"
optimalInitiativeId: "-1"
presentCO2Emissions: "2 343"
presentEnergy: {,…}
presentEnergyConsumption: "24 338"
presentEnergyCost: "21 904"
presentEnergyCostAsString: "kr 21 904"
presentEnergyCostSummary: "..."
presentEnergyRatingImage: "D_5.png"
recommendedInitiativeIds: []
saving: 2592
savingsAsString: "kr 2 592"
tek10Energy: {,…}
upgradedEnergyCostSummary: "..."
upgradedEnergyRatingImage: "C_4.png"
我想以 JSON 形式检索此数据,

但看到此数据被请求有效负载下的值更改,我还必须能够在请求有效负载中使用新值发送请求,以便检索所需的 JSON 结果。

到目前为止,我尝试过,代码主要取自此链接。

$url = 'http://energiportalen.no/Energianalyse/MinBolig/?municipality=0111&area=187&yoc=1989&type=2';
$data = array('Area' => '199', 'initiatives' => '["1"]');
// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'  => "Content-type: application/json'r'n",
        'method'  => 'POST',
        'content' => http_build_query($data),
    ),
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }
var_dump($result);

这样做的结果是bool(false),因为它可能是错误的代码。

假设我必须将"header"=>"内容类型:application/x-www-form-urlencoded''r'"更改为application/json,因为这是我在"网络"选项卡中的"请求标头"下看到的内容。我真的不知道这是否正确。

我还添加了

$data = array('Area' => '199', 'initiatives' => '["1"]');

我希望上面的代码行更改"请求有效负载"下的"区域"和"倡议"设置,以便我可以在"请求有效负载"下检索新值网络中的预览

所以我的问题是:

如何通过对此URL的POST请求send参数,并检索位于Chrome中网络> Energi>预览下的数据,作为外部站点的JSON结果。

我位于一个单独的网站上,我想检索这些数据。

这可能吗?任何帮助,不胜感激。

我认为您要求的是一个PHP方法,该方法将发布到输出JSON的服务。

这可以在 PHP 中完成,在 curl 的帮助下。示例函数:

/*
    post data to a service url that returns JSON
    $urlAbs  absolute path of the service
    $data    data to post to the service
*/
function postToService_php( $urlAbs, $data ) {
    $dataJSON = json_encode($data);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $urlAbs);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
    curl_setopt($ch, CURLOPT_POSTFIELDS, $dataJSON);                                                                  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
        'Content-Type: application/json',                                                                                
        'Content-Length: ' . strlen($dataJSON))                                                                       
    );
    $resultJSON = curl_exec($ch);
    return $resultJSON;
}