How to send byte[] array in retrofit

后端 未结 2 1338
半阙折子戏
半阙折子戏 2020-12-16 21:09

How do you send byte[] array in retrofit call. I just need to send over byte[]. I get this exception when I have been trying to send a retrofit call.

ret

相关标签:
2条回答
  • 2020-12-16 22:03

    For retrofit2:

    @POST("/send")
    void upload(@Body RequestBody bytes, Callback<String> cb);
    

    usage:

    byte[] params = ...
    RequestBody body = RequestBody.create(MediaType.parse("application/octet-stream"), params);
    remoteService.upload(body, new Callback<String>() {
        @Override
        public void success(String s, Response response) {
            //Success Handling
        }
    
        @Override
        public void failure(RetrofitError retrofitError) {
            //Error Handling
        }
    }); 
    
    0 讨论(0)
  • 2020-12-16 22:06

    For this purpose you can use TypedByteArray

    Your Retrofit service will look like this:

    @POST("/send")
    void upload(@Body TypedInput bytes, Callback<String> cb);
    

    Your client code:

        byte[] byteArray = ...
        TypedInput typedBytes = new TypedByteArray("application/octet-stream",  byteArray);
        remoteService.upload(typedBytes, new Callback<String>() {
            @Override
            public void success(String s, Response response) {
                //Success Handling
            }
    
            @Override
            public void failure(RetrofitError retrofitError) {
                //Error Handling
            }
        }); 
    

    "application/octet-stream" - instead this MIME-TYPE, you maybe want to use your data format type. Detail information you can find here: http://www.freeformatter.com/mime-types-list.html

    And Spring MVC controller (if you need one):

    @RequestMapping(value = "/send", method = RequestMethod.POST)
    public ResponseEntity<String> receive(@RequestBody byte[] data) {
        //handle data
        return new ResponseEntity<>(HttpStatus.CREATED);
    }
    
    0 讨论(0)
提交回复
热议问题