Can signed bytes be read from a stream?

I'm trying to read bytes sent by a java servlet into a C# application, so far, I haven't been able to get anything more than gibberish from the servlet using normal streams in C#. I've tried various forms of decoding, but haven't found a working way to read sbytes into a c# application from an http source.

The servlet bytes are sent with

Edited Code

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    ServletOutputStream resp = response.getOutputStream();
    try{
        resp.write("test".getBytes("UTF-8"));
    }
    catch(Exception e){
        //Do Nothing
    }

C# reads in with

        try
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://path.to/servlet");
            req.Method = "POST";
            req.ContentType = "text/html";
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

            string text;
            using (var reader = new StreamReader(resp.GetResponseStream()))
            {
                text = reader.ReadToEnd();
                Console.WriteLine(text);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

I end up with two question marks or the same two ascii symbols.

Does anyone have any idea how to do stream these Java bytes into a C# application?

Jon Skeet
people
quotationmark

Two problems:

  • You're using the platform-default encoding in both C# and Java. That's almost always a bad choice. Specify the encoding explicitly in Java - UTF-8 is usually a good choice. (That's also the default for most .NET code.)
  • You're ignoring the return value of Stream.Read; in general you should use that to work out how much data you've actually received. In this case, however, it would be a much better idea to use StreamReader:

    string text;
    // Uses UTF-8 implicitly
    using (var reader = new StreamReader(httpResponse.GetResponseStream())
    {
        text = reader.ReadToEnd();
    }
    

The signedness of bytes in Java is irrelevant here.

(Additionally, why are you using new String("test")? What do you think that will do over just using "test"?)

people

See more on this question at Stackoverflow