【发布时间】:2017-05-01 01:05:54
【问题描述】:
我有一个带有ESP-12E 的NodeMCU 1.0,并使用Arduino IDE 在上面编写代码。
我想将POST 消息发送到我的网络服务器上的远程php 页面,其中包含来自我的模块的值,但首先我需要发送一些东西......
我尝试了许多来自不同来源和代码 sn-ps 的不同示例,但似乎没有一个有效。发送的方法
GET 方法正在运行,我可以从 php 页面中检索数据,但无法发送给它们。
我的代码:
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
const char* ssid = "SomeWireless";
const char* password = "12345";
String server = "www.example.net"; // www.example.com
void setup() {
Serial.begin(115200);
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
jsonPOST();
myPOST();
myGET();
}
void myPOST() {
HTTPClient http;
http.begin("http://example.net/asd/recv.php");
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
http.POST("title=foo");
http.writeToStream(&Serial);
http.end();
delay(1000);
}
void jsonPOST() {
WiFiClient client;
if (client.connect("example.net", 80)) {
Serial.println("Connected to server");
// Make the HTTP request
int value = 2.5; // an arbitrary value for testing
String content = "{\"JSON_key\": " + String(value) + "}";
client.println("POST /asd/recv.php HTTP/1.1");
client.println("Host: example.net");
client.println("Accept: */*");
client.println("Content-Length: " + String(content.length()));
client.println("Content-Type: application/json");
client.println();
client.println(content);
}
delay(1000);
}
void myGET() {
if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
HTTPClient http; //Declare an object of class HTTPClient
http.begin("http://www.exmaple.net/asd/btnCheck.php"); //Specify request destination
int httpCode = http.GET(); //Send the request
if (httpCode > 0) { //Check the returning code
String payload = http.getString(); //Get the request response payload
Serial.println(payload); //Print the response payload
}
http.end(); //Close connection
}
delay(1000);
}
我的 php:
$test = $_POST['title'];
echo $test;
//JSON
$json = file_get_contents('php://input');
$obj = json_decode($json);
echo $obj;
编辑:我想提一下,网络服务器可以接受 POST 消息,而且我有一个经销商类型的帐户,所以我无法完全控制服务器。
关于这件事的任何建议,都是值得的。 2 天以来,我一直在用它来敲打我的头。
谢谢!
【问题讨论】:
标签: php post arduino esp8266 nodemcu