如何在android中发送特定格式的请求,例如
[RequestID-1byte] [sourceID-1byte] [datalen-4byte][数据部分]
我不确定,但我认为你可以这样做与Volley Library
:
StringRequest mStringRequest = new StringRequest(Request.Method.POST, URL_VALIDATE, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// code for response here
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// code for error response here
}
}) {
@Override
protected Map<String, Byte> getParams() {
Map<String, Byte> params = new HashMap<>();
// the POST parameters:
params.put("RequestID", byte1);
params.put("sourceID", byte2);
params.put("datalen", byte3);
return params;
}
};
Volley.newRequestQueue(this).add(mStringRequest);
希望有帮助!
使用服务器-客户端套接字编程
正在编写示例代码。
public class Packet {
private byte requestID;
private byte sourceID;
private byte[] data;
public Packet(byte requestID, byte sourceID, byte[] data) {
this.requestID = requestID;
this.sourceID = sourceID;
// TODO: add exception handling for data length > 65535, data length more 4byte
this.data = data;
}
public byte[] getData() throws IOException{
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
byteStream.write(requestID);
byteStream.write(sourceID);
if(data.length<0xff) // if data length < 255, data byte is 2
byteStream.write(0);
byteStream.write((short)data.length);
byteStream.write(data);
byteStream.close();
return byteStream.toByteArray();
}
}
和套接字I/O
Socket socket = new Socket(somehost, someport);
InputStream inStream = socket.getInputStream();
OutputStream outStream = socket.getOutputStream();
...
...
byte requestID = 1;
byte sourceID = 2;
byte data[] = ....
Packet packet = new Packet(requestID,sourceID,data);
outStream.write(packet.getData());
outStream.flush();
...
...