我在 Android 中使用 Nanohttpd 来创建一个从同一个应用的其他实例接收字节的应用。在我的情况下,我的应用程序正常工作并将数据正常发送到Web服务,但是当我尝试在此应用程序的两个实例之间发送数据时,当我调试时,我看到了奇怪的字节,如垃圾或不同的编码。我尝试使用NanoHttpd中的InputStream。
我的代码使用java代码发送数据:
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();
}
}
}
在Android中,我想从最后一个代码读取字节,我的代码是:
@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());
}
}
我需要使用main java示例来发送字节,有时我需要writeUtf等,因为我的应用程序运行相同。