Post запрос с JSON и Authorization Header
- Войдите на сайт для отправки комментариев
Доброго времени суток. Пытаюсь написать для Ардуино POST запрос на сервер. Весь скеч на основе примера WebClient
/* Web client This sketch connects to a website (http://www.google.com) using an Arduino Wiznet Ethernet shield. Circuit: * Ethernet shield attached to pins 10, 11, 12, 13 created 18 Dec 2009 by David A. Mellis modified 9 Apr 2012 by Tom Igoe, based on work by Adrian McEwen */ #include <SPI.h> #include <Ethernet.h> // Enter a MAC address for your controller below. // Newer Ethernet shields have a MAC address printed on a sticker on the shield byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // if you don't want to use DNS (and reduce your sketch size) // use the numeric IP instead of the name for the server: //IPAddress server(178,170,244,14); // numeric IP for Google (no DNS) char server[] = "http://fcm.googleapis.com"; // name address for Google (using DNS) char ServerKey[] = "AAAAPNK56lw:APA91bHyjROWuWsqm6tC_gel_j571G1TQFGzW0fHVFgkZeao3XW0I65_7FqttzYYrycpBLmmIzLgymp4N9DlM9_T5r411XkbCippepCdTyBs9fPFcCNA03va5kcqU4SnlvLvkmttzzM_"; String Data ="{\"registration_ids\":[\"APA91bHGh9fdAmxxGeFGs5dQShJAtb1zBip75QoNeFEyDCSWQ9eNsraoq51HVS9nwIdgGEDhs2nDV19oAEezZZpkHavuQc8sx8bTlzE6osVwHxWO5cuslp79LnicfcBmwnsYINtymvab\"],\"priority\":\"high\",\"notification\":{\"body\":\"test\",\"title\":\"UmDom\",\"sound\":\"default\",\"icon\":\"1\"},\"data\":{\"message\":\"test\",\"title\":\"UmDom\"}}"; // Set the static IP address to use if the DHCP fails to assign IPAddress ip(192, 168, 1, 10); IPAddress myDns(192, 168, 1, 1); IPAddress myGate(192, 168, 1, 1); // Initialize the Ethernet client library // with the IP address and port of the server // that you want to connect to (port 80 is default for HTTP): EthernetClient client; unsigned long beginMicros, endMicros; unsigned long byteCount=0; void setup() { // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } // start the Ethernet connection: Serial.println("Initialize Ethernet with DHCP:"); if (Ethernet.begin(mac) == 0) { Serial.println("Failed to configure Ethernet using DHCP"); // no point in carrying on, so do nothing forevermore: // try to congifure using IP address instead of DHCP: Ethernet.begin(mac, ip, myDns); } else { Serial.print(" DHCP assigned IP "); Serial.println(Ethernet.localIP()); } // give the Ethernet shield a second to initialize: delay(1000); Serial.print("connecting to "); Serial.print(server); Serial.println("..."); // if you get a connection, report back via serial: if (client.connect(server, 80)) { Serial.println("connected"); // Make a HTTP request: client.println("POST /fcm/send HTTP/1.1"); client.println("Content-Type: application/json"); client.print("Authorization: key="); client.println(ServerKey); //client.println("Authorization: key=AAAAPNK56lw:APA91bHyjROWuWsqm6tC_gel_j571G1TQFGzW0fHVFgkZeao3XW0I65_7FqttzYYrycpBLmmIzLgymp4N9DlM9_T5r411XkbCippepCdTyBs9fPFcCNA03va5kcqU4SnlvLvkmttzzM_"); client.println("Host: http://fcm.googleapis.com"); client.print("Content-Length: "); client.println(Data.length()); client.println(); client.println(Data); client.println("Connection: close"); } else { // if you didn't get a connection to the server: Serial.println("connection failed"); } beginMicros = micros(); } void loop() { // if there are incoming bytes available // from the server, read them and print them: int len = client.available(); if (len > 0) { byte buffer[80]; if (len > 80) len = 80; client.read(buffer, len); Serial.write(buffer, len); // show in the serial monitor (slows some boards) byteCount = byteCount + len; } // if the server's disconnected, stop the client: if (!client.connected()) { endMicros = micros(); Serial.println(); Serial.println("disconnecting."); client.stop(); Serial.print("Received "); Serial.print(byteCount); Serial.print(" bytes in "); float seconds = (float)(endMicros - beginMicros) / 1000000.0; Serial.print(seconds, 4); float rate = (float)byteCount / seconds / 1000.0; Serial.print(", rate = "); Serial.print(rate); Serial.print(" kbytes/second"); Serial.println(); // do nothing forevermore: while (true); } }
Получаю ответ 400 Bad Request/
Точно знаю, что сервис рабочий, все отрабатывает в программе написанной на Delphi и в REST Client (плагин к Chrome https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo)
Собственно несколько вопросов к гуру (я не силен в написании запросов)
1. В заголовке должен быть Authorization: key=хххх;
Правильная ли запись client.println("Authorization: key=xxxxx"); Или заголовки надо как-то отдельно выделять.
2. ТО же самое касается client.println("Content-Type: application/json"); Как правильно послать строку json?
Заранее спасибо за ответы!!!!
В строке 76 какой-то дикий заголовок, заголовок Host не должен содержать ссылок. Это из того, что сразу бросилось в глаза.
Не, это так вставилось.
Там такая строка client.println("Host: http://fcm.googleapis.com"); (вот опять))))))
Где то на просторах интернета читал, что запрос нужно перекодировать, но у меня в нем даже пробелов нигде нет
Не, это так вставилось.
Там такая строка client.println("Host: http://fcm.googleapis.com"); (вот опять))))))
У вас имя хоста с http? Это неправильно, должно быть
client.println("Host: fcm.googleapis.com")
Спасибоо тебе, мил человек!!!! Спас ты меня!!!!
Все правильно, client.println("Host: fcm.googleapis.com")
Респект!!!
upd final: все вопросы отпали, победил.