发送POST请求以使用PHP

时间:2016-02-18 09:14:43

标签: php json post request

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

首先我去this site。然后,使用Google Chrome浏览器检查网站,然后转到“网络”标签。打开此窗口时,我将 Varmepumpe - luft til luft INGEN 更改为实际网站上的 LITEN 。名称 Energi 现在显示在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请求更改这些参数,以便将它们发送进行重新计算,以便我可以从外部站点的Network as JSON下的Preview选项卡中检索信息?

以下是预览标签的示例:

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结果。

这是我到目前为止所尝试的内容,代码主要来自this link

$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),因为它可能是错误的代码。

我认为我必须更改'标题' => "内容类型:application / x-www-form-urlencoded \ r \ n", application / json ,因为这是我在下看到的“网络”标签中的“请求标题”。如果这是正确的,我真的不知道。

我还添加了

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

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

所以我的问题是:

我如何send参数对此网址发出POST请求并检索位于网络>下的数据? Energi>使用外部网站在Chrome中预览JSON结果。

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

这甚至可能吗?任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

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

这可以在PHP的帮助下完成。示例功能:

  sayHeroName(hero: Hero) {
    hero.speak();
  }