I am using Nanohttpd in Android to create an app that receives bytes from other instance of the same app. In my case, my application works and send data normally to a web service, but when I tried to send data between two instance of this application, when I debugged I saw strange bytes like trash or for example different encoding. I tried to use InputStream from NanoHttpd.
My code send data with a java code:
public class MainTest {
public static void main(String[] args) {
try {
URL url = new URL("http://192.168.0.215:8080");
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setUseCaches(false);
httpConnection.setDoInput(true);
httpConnection.setDoOutput(true);
httpConnection.setChunkedStreamingMode(4096);
httpConnection.setConnectTimeout(1000 * 5);
httpConnection.setReadTimeout(1000 * 5);
httpConnection.setRequestMethod("POST");
httpConnection.addRequestProperty("Content-Type", "application/octet-stream");
httpConnection.addRequestProperty("Transfer-Encoding", "chunked");
httpConnection.addRequestProperty("Connection", "close");
OutputStream out = httpConnection.getOutputStream();
DataOutputStream dataOutputStream = new DataOutputStream(out);
dataOutputStream.writeInt(37);
dataOutputStream.close();
httpConnection.getResponseMessage();
} catch (Exception e) {
e.printStackTrace();
}
}
}
In Android, I want to read bytes from the last code, my code is:
@Override
public Response serve(IHTTPSession session) {
Method method = session.getMethod();
try {
if (Method.POST.equals(method)) {
DataInputStream in = new DataInputStream(session.getInputStream());
int value = in.readInt();
Log.d("nextValue: ", value); // expected 37
} else {
return executeGet(session);
}
} catch (Exception ex) {
return newFixedLengthResponse(Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT,
"SERVER MOBILE INTERNAL ERROR: : " + ex.getMessage());
}
}
I need to use main java sample to send bytes, sometimes I need to writeUtf etc., because I've an app that works the same.