4

Доброе время суток! При вызове Get метода, catch(Exception ex) выводит ошибку "Сервер нарушил протокол. Section=ResponseStatusLine.

код на клиенте Метод get-запроса:

  public String URL = "http://192.168.16.254:8080/blinkSs";
    string r = "";
    private string GET(string sUrl, string Data)
    {

        System.Net.WebRequest req = System.Net.WebRequest.Create(sUrl + "?" + Data);
        System.Net.WebResponse resp = req.GetResponse();
        System.IO.Stream stream = resp.GetResponseStream();
        System.IO.StreamReader sr = new System.IO.StreamReader(stream);
        string Out = sr.ReadToEnd();
        sr.Close();
        return Out;

    }

Вызываю метод GET вот так:

if (e.KeyCode == Keys.Up)
            {
                try
                {
                    r = "oske";
                    String a=GET(URL, r);
                    MessageBox.Show(a);
                }
                catch(Exception ex) {
                    MessageBox.Show("error" + " " + ex.Message);
                }
            }

код на сервере:

void setup() {     
  Serial.begin(115200);  
  pinMode(13, OUTPUT); //Rele 1
  //pinMode(12, OUTPUT);  //Rele 2
}
int f = 0;
String com_get = "";//
void loop() {
  boolean has_request = false;
  String in = "";
  if (Serial.available()) {
    in = "";
    while (true) {  // should add time out here
      while (Serial.available() == false) {}
      in += (char)(Serial.read());//тут хттп запрос, урл адресс
      if (in.endsWith("\r\n\r\n")) {//если первая строка (string) завершается символом, содержащимся в строке string2
        has_request = true;  break;
      }
    }   
  }
  if (has_request) {
    int i1 = in.indexOf("GET /blinkSs?"), i2;//13 символов
    if (i1 != -1) {
      i2 = in.indexOf(" ", i1+13);//кол. символов с 13ого
      f = in.substring(i1+13, i2).toInt();//запрос
      com_get=in.substring(i1+13, i2);
    }      


    //Serial.println("HTTP/1.1 200 OK\nContent-Type: text/html\nConnection: close");
     //String sr = "<!DOCTYPE HTML>";
     //Serial.println(sr);
    // Serial.println("<html>");
     //Serial.println("<head>");
     //Serial.println("</head>");
     //Serial.println("<body>");
    if (com_get=="oske") {f=1; Serial.println("Comando 1. oske"); } //↑
    if (com_get=="aska") {f=2; Serial.println("Comando 2. aska"); }//↓
    if (com_get=="kren_unga") {f=3; Serial.println("Comando 3. kren_unga"); }// /
    if (com_get=="kren_sulga") {f=1; Serial.println("Comando 1. kren_sulga"); }// \

   //Serial.println("</body>");
   //Serial.println("</html>\n");
    has_request = false;
  }
switch (f){
  case 1:
   digitalWrite(13, HIGH);
   break;
  case 2:
   digitalWrite(13, LOW);
   break;  
   f=0;
   Serial.end();

}  

}
1
  • 2
    Используйте HttpWebResponse вместо того чтобы самому протокол реализовывать.
    – Alex78191
    12 июл 2017 в 4:43

2 ответа 2

3

В файл app.config добавьте

<system.net> 
  <settings> 
   <httpWebRequest useUnsafeHeaderParsing="true" /> 
  </settings> 
</system.net> 

Задание этого свойства игнорирует ошибки проверки, возникающие при анализе HTTP.

1
  • Это точно помогает! Спасибо! 6 фев 2018 в 10:42
2

Очевидно же, что ты на сервере код состояния Status-Line не отправляешь. Изучи RFC https://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html

       Response      = Status-Line               ; Section 6.1
                       *(( general-header        ; Section 4.5
                        | response-header        ; Section 6.2
                        | entity-header ) CRLF)  ; Section 7.1
                       CRLF
                       [ message-body ]          ; Section 7.

enter image description here

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.