Ravi-A-Doer Ravi-A-Doer - 28 days ago 9
Java Question

REST API: InputStream Copying (dovetailing) Failing for Big Files

Using Jersey 1.8, I am developing a REST API to upload files. In turn, I am using a service providers REST API to upload the files to their site. The flow looks like:

Browser --> My REST using Jersey server side; and then using Apache HTTP Client to make onward REST calls --> Service Provider's REST.

When I upload small files (<1MB), it all works fine. But when the file size increases it gives me following error.

A JSONObject text must begin with '{' at character 0


I suspect the error is due to the stream getting "cut" the mid-way. What is the issue with the following code snippet (I have removed the irrelevant code).

@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public Response uploadDocument(@FormDataParam("document") InputStream inputStream) {
FilenetAdapter filenet = new FilenetAdapter();
String documentId = filenet.uploadDocument(inputStream);
// return the Jersey call - code removed for bravity
}

//FilenetAdapert.uploadDocument function
public String uploadDocument(InputStream inputStream) {

HttpPost request = new HttpPost(serviceUrl);
request.setEntity(buildMultipartEntity(metadata, inputStream));

CloseableHttpClient client = HttpClientBuilder.create().build();
CloseableHttpResponse response = client.execute(request);
//consume the response - code removed for bravity
}

private HttpEntity buildMultipartEntity(JSONObject metadata, InputStream inputStream)
throws IOException, URISyntaxException, JSONException {

// Build a multipart HTTP request according to RFC1341
MultipartEntityBuilder builder = MultipartEntityBuilder.create();

// Set request metadata
StringBody stringBody = new StringBody(metadata.toString(), ContentType.TEXT_PLAIN);
FormBodyPartBuilder bodyPartBuilder = FormBodyPartBuilder.create();
bodyPartBuilder.setName("metadata");
bodyPartBuilder.setBody(stringBody);
FormBodyPart mdata = bodyPartBuilder.build();
builder.addPart(mdata);

// Set request content
ContentBody cbFile = new InputStreamBody(inputStream, ContentType.APPLICATION_OCTET_STREAM);
builder.addPart("file", cbFile);
return builder.build();
}

Answer

The service provider changed their server configuration. That resolved the issue.