Search code examples
c#httpflutterresponsehttp-status-codes

Flutter-Framework, C# http server and an invalid JSON-Header s Invalid response status code


since i'm new to the flutter.io-app-framework and c#-http-sever (request and response), i'm struggling with an error for about two weeks or so. I'm completly new to JSON.

My problem is an invalid JSON header. To be precise, my Android Studio is saying something like "error: HttpException: Invalid response status code, uri = http://127.0.0.1:2508/user/1".

The error is only occurring when using the app for a http request. My firefox and chrome are doing fine. The result is shown as it should.

In my dart/flutter app, i'm just sending a http get request which does look like the following:

 Future<String> getData() async {
    var response = await http.get(
        Uri.encodeFull("http://127.0.0.1:2508/user/1"),
        headers: {"Accept": "text/json"});

    this.setState(() {
      user = json.decode(response.body);
      print(user[0]);
    });

    return "Success!";
  }

My c# server code looks like this: private void HandleClient(TcpClient client) {

  StreamReader reader = new StreamReader(client.GetStream());
  StreamWriter writer = new StreamWriter(client.GetStream());
  String request = reader.ReadLine();
  if (!String.IsNullOrEmpty(request))
  {
    Log.WriteLine("\nRequest: \n" + request);
    string[] tokens = request.Split(' ');
    Log.WriteLine("~~~~~ Tokens ~~~~~");
    foreach (String token in tokens)
    {
      Log.WriteLine("~ " + token);
    }
    Log.WriteLine("~~~~~~~~~~~~~~~~~~\n");
    String[] cmds = tokens[1].Split('/');
    String cmd = cmds[1].ToUpper();
    String json = "";
    switch (cmd)
    {
      case "USER":
        if ((cmds.Length >= 3) && (cmds[2] != ""))
        {
          json += Tools.toJSON(Data.GetBenutzer(Convert.ToInt16(cmds[2])));
        }
        break;
      default:
        break;
    }

    writer.WriteLine(VERSION + " \n200 OK\nServer: " + NAME + "\nContent-Type: text/json\nAccess-Control-Allow-Origin: *\n");
    writer.WriteLine(json);

    Log.WriteLine("~~~~~~ Json ~~~~~~\n" +
                  json + "\n" +
                  "~~~~~~~~~~~~~~~~~~\n");

    writer.Flush();
    writer.Close();
    writer.Dispose();


  }

}

Is anything essential missing in the JSON response? Maybe you have another inspiring idea that can help me.


Solution

  • First off, I'd highly recommend using a http server package that handles the low level stuff like writing headers for you! Someone has gone to the effort of doing this stuff, verifying that it meets the HTTP RFC, testing it, and then giving it away for free!

    If this is for an assignment or to learn http, or you have some other good reason, fair enough. But otherwise, there's almost no point in writing something like this from scratch where you could introduce bugs that are hard to figure out. Not only could you introduce http errors, but you'll have to make sure you do threading properly or you could run into problems when you get more traffic. And you'll save a lot of time because someone else has already figured out the hard stuff, so you can concentrate on making whatever it is you actually want to make.


    But for your problem - it appears that the http part of the response isn't formatted quite right because flutter isn't recognizing the 200 response code you're trying to send (and therefore isn't reading it).

    It's hard to tell without you actually posting what the http response looks like in full, but I think it's to do with an extra line feed.

    You have writer.WriteLine(VERSION + " \n200 OK\nServer: "... but I think it should be writer.WriteLine(VERSION + " 200 OK\nServer: " (assuming version is something like HTTP/1.1).

    Also you should be aware that the HTTP protocol actually wants \r\n for line feeds, although all modern servers/clients should be able to support just '\n' as well. But it's always better to follow the protocol specification.