1. 程式人生 > >okHttp+protobuf實現okhttp post二進位制流至伺服器

okHttp+protobuf實現okhttp post二進位制流至伺服器


 
//上次上傳的有些錯誤,這次親測是正確的,本人目前也在學習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(); } } }); }