版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34928991/article/details/70036301
//上次上传的有些错误,这次亲测是正确的,本人目前也在学习protobuf,有什么问题可以评论 互相讨论
public void okHttpPost(String url) throws IOException { Integer head = 0XFF; long playerId = 0; long sessionId=0; int commandId = CommandMessage.CommandEnum.CMD_GET_DICT_INFOS.getNumber() ; //我测了一个不需要传参数的对象 ModuleMessage.Empty_Req player = ModuleMessage.Empty_Req.newBuilder().build(); // AoneProtoMessage.Test_Req.Builder aoneProtoMsg = AoneProtoMessage.Test_Req.newBuilder(); // aoneProtoMsg.setParam1("").setParam2(commandId); // AoneProtoMessage.Test_Req player= aoneProtoMsg.build(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(outputStream); //服务器要求需要拼接的字节位 int size = 4+player.toByteArray().length; dos.writeInt(head); dos.writeLong(playerId); dos.writeLong(sessionId); dos.writeInt(size); dos.writeInt(commandId); //dos.write(player.toByteArray()); player.writeTo(dos); text.setText(Arrays.toString(outputStream.toByteArray())); OkHttpClient client = new OkHttpClient(); client.newBuilder().connectTimeout(5, TimeUnit.SECONDS); client.newBuilder().readTimeout(5, TimeUnit.SECONDS); client.newBuilder().writeTimeout(5, TimeUnit.SECONDS); final RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"),outputStream.toByteArray()); final Request request = new Request.Builder().url(url).post(requestBody).build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(">>>>>>>>>>","onFailure"+e.toString()); } @Override public void onResponse(Call call, Response response) throws IOException { byte a[] = response.body().bytes(); byte b[] = new byte[a.length-12]; //这里也是服务器返回前面字节数组所占的用于验证的字符 我们服务器是要截去前12位 保留12位以后为有效data System.arraycopy(a,12,b,0,a.length-12); Log.e(">>>>>>>>>>","onResponse"+Arrays.toString(a)); // //AoneProtoMessage.Test_Req req= AoneProtoMessage.Test_Req.parseFrom(dis); try{ //反序列化(亲测有效) AoneProtoMessage.GetDictInfo_Rsp rsp = AoneProtoMessage.GetDictInfo_Rsp.parseFrom(b); Map<String,ModuleMessage.CategoryDict> map = rsp.getCategoryDict(); Log.e(">>>","Count:"+rsp.getCategoryDictCount()+"/r/n" + "AllMap"+ map.toString()); }catch (InvalidProtocolBufferException e){ e.printStackTrace(); } } }); }