WebClient. Не выполняется запрос

Vladimir74
Offline
Зарегистрирован: 17.12.2017


Всем привет. Есть сервер который принимает число и выводит его. Пытаюсь выполнить GET запрос но ничего не происходит.
 
 
 
 
 
Клиент:
 
#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(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "http://wcfrestservice222.azurewebsites.net";    // name address for Google (using DNS)
 
// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 177);
 
// 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;
 
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:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.println("connecting...");
 
  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {
    Serial.println("connected");
    // Make a HTTP request:
    client.println("GET /Service1/ddd/7 HTTP/1.1");
    client.println("Host: http://wcfrestservice222.azurewebsites.net");
    client.println("Connection: close");
    client.println();
  } else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}
 
void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }
 
  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
 
    // do nothing forevermore:
    while (true);
  }
}
 
Сервер:
 
 
 public class Service1
    {
        // TODO: Implement the collection resource that will contain the SampleItem instances
 
        [WebInvoke(UriTemplate = "/rrr", Method = "GET")]
        public string GetCollection()
        {
            // TODO: Replace the current implementation to return a collection of SampleItem instances
            return SampleItem.Id.ToString();
        }
 
        [WebInvoke(UriTemplate = "/ddd/{id}", Method = "GET")]
        public string Create(string id)
        {
            SampleItem.Id = Int32.Parse(id);
            // TODO: Add the new instance of SampleItem to the collection
            return "Hello Vova";
        }
 
        [WebGet(UriTemplate = "{id}")]
        public SampleItem Get(string id)
        {
            // TODO: Return the instance of SampleItem with the given id
            throw new NotImplementedException();
        }
 
        [WebInvoke(UriTemplate = "{id}", Method = "PUT")]
        public SampleItem Update(string id, SampleItem instance)
        {
            // TODO: Update the given instance of SampleItem in the collection
            throw new NotImplementedException();
        }
 
        [WebInvoke(UriTemplate = "{id}", Method = "DELETE")]
        public void Delete(string id)
        {
            // TODO: Remove the instance of SampleItem with the given id from the collection
            throw new NotImplementedException();
        }
 
    }
 
 
 
ЕвгенийП
ЕвгенийП аватар
Offline
Зарегистрирован: 25.05.2015

Vladimir74 пишет:



Всем привет. 

Привет!

Vladimir74 пишет:

Есть сервер который принимает число и выводит его. Пытаюсь выполнить GET запрос но ничего не происходит.

И что? Вы просто решили проинформировать нас? Или у Вас есть какие-то вопросы или пожелания к сообществу? Если есть, так озвучьте, не стесняйтесь.

 

 

Vladimir74
Offline
Зарегистрирован: 17.12.2017

Выполняю запрос:

 client.println("GET /Service1/ddd/7 HTTP/1.1");
    client.println("Host: http://wcfrestservice222.azurewebsites.net");
    client.println("Connection: close");
    client.println();
 
 
На сервер должно прийти число 7:
 
 [WebInvoke(UriTemplate = "/ddd/{id}", Method = "GET")]
        public string Create(string id)
        {
            SampleItem.Id = Int32.Parse(id);
            // TODO: Add the new instance of SampleItem to the collection
            return "Hello Vova";
        }
 
        [WebInvoke(UriTemplate = "/rrr", Method = "GET")]
        public string GetCollection()
        {
            // TODO: Replace the current implementation to return a collection of SampleItem instances
            return SampleItem.Id.ToString();
        }
 
но этого не происходит, может кто подскажет что не так.  Запросы проверял клиентом тестером HTTP-запросов, все работает.

 

ЕвгенийП
ЕвгенийП аватар
Offline
Зарегистрирован: 25.05.2015

Vladimir74 пишет:
может кто подскажет что не так
В первую очередь, Вы не так вставили код. В таком виде, большинство из обитателей форума его просто не будут читать (я, например, не читал).

Vladimir74
Offline
Зарегистрирован: 17.12.2017
#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(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "http://wcfrestservice222.azurewebsites.net";    // name address for Google (using DNS)

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 177);

// 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;

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:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }
  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.println("connecting...");

  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {
    Serial.println("connected");
    // Make a HTTP request:
    client.println("GET /Service1/ddd/7 HTTP/1.1");
    client.println("Host: http://wcfrestservice222.azurewebsites.net");
    client.println("Connection: close");
    client.println();
  } else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    while (true);
  }
}

Ссылка на севрер неправильно отображается, когда вставляю код(http://wcfrestservice222.azurewebsites.net)

Сервер:

 [WebInvoke(UriTemplate = "/ddd/{id}", Method = "GET")]
        public string Create(string id)
        {
            SampleItem.Id = Int32.Parse(id);
            // TODO: Add the new instance of SampleItem to the collection
            return "Hello Vova";
        }
[WebInvoke(UriTemplate = "/rrr", Method = "GET")]
        public string GetCollection()
        {
            // TODO: Replace the current implementation to return a collection of SampleItem instances
            return SampleItem.Id.ToString();
        }

 

DIYMan
DIYMan аватар
Offline
Зарегистрирован: 23.11.2015

Заголоков HOST должен быть без http:// - это как минимум.

Vladimir74
Offline
Зарегистрирован: 17.12.2017

Спасибо, все заработало