Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

java - Jersey REST Client : Posting MultiPart data

I am trying to write a Jersey client app which can post multi part form data to a Restful Jersey service. I need to post a CSV file with the data and a JSON with meta-data. I am using Jersey client 1.18.3. Here is my code (some names have been changed for company confidentiality )...

Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/mariam/service/playWithDad");


    FileDataBodyPart filePart = new FileDataBodyPart("file", 
            new File("C:/Users/Admin/Desktop/input/games.csv"));

    String playWithDadMetaJson
    = "{
"
    + "    "sandboxIndicator": true,
"
    + "    "skipBadLines": false,
"
    + "    "fileSeparator": "COMMA",
"
    + "    "blockSize": false,
"
    + "    "gameUUID": "43a004c9-2130-4e75-8fd4-e5fccae31840",
"
    + "    "useFriends": "false"
"
    + "}
"
    + "";

    MultiPart multipartEntity = new FormDataMultiPart()
    .field("meta", playWithDadMetaJson, MediaType.APPLICATION_JSON_TYPE)
    .bodyPart(filePart);

    ClientResponse response = webResource.type(MediaType.MULTIPART_FORM_DATA_TYPE).post(multipartEntity);

Right now I am getting a compile error at the last line saying it cannot convert from void to ClientResponse.

I got some guidance on the RestFul service itself previously from this post..

Java Rest Jersey : Posting multiple types of data (File and JSON)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Follow jersey documentation, they provide sample client code. Here is the snippet to post a multipart request:

final MultiPart multiPartEntity = new MultiPart()
        .bodyPart(new BodyPart().entity("hello"))
        .bodyPart(new BodyPart(new JaxbBean("xml"), MediaType.APPLICATION_XML_TYPE))
        .bodyPart(new BodyPart(new JaxbBean("json"), MediaType.APPLICATION_JSON_TYPE));

final WebTarget target = // Create WebTarget.
final Response response = target
        .request()
        .post(Entity.entity(multiPartEntity, multiPartEntity.getMediaType()));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...