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?
Two problems:
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"
?)
See more on this question at Stackoverflow