Posting a File and Associated Data to a RESTful WebService preferably as JSON

后端 未结 11 980
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 10:45

This is probably going to be a stupid question but I\'m having one of those nights. In an application I am developing RESTful API and we want the client to send data as JSON

11条回答
  •  执念已碎
    2020-11-22 11:40

    You could try using https://square.github.io/okhttp/ library. You can set the request body to multipart and then add the file and json objects separately like so:

    MultipartBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("uploadFile", uploadFile.getName(), okhttp3.RequestBody.create(uploadFile, MediaType.parse("image/png")))
                    .addFormDataPart("file metadata", json)
                    .build();
    
            Request request = new Request.Builder()
                    .url("https://uploadurl.com/uploadFile")
                    .post(requestBody)
                    .build();
    
            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
    
                logger.info(response.body().string());
    

提交回复
热议问题