首页 文章

Jersey REST Client:发布MultiPart数据

提问于
浏览
3

我正在尝试编写一个Jersey客户端应用程序,它可以将多部分表单数据发布到Restful Jersey服务 . 我需要发布带有数据的CSV文件和带有元数据的JSON . 我正在使用Jersey客户端1.18.3 . 这是我的代码(一些名称已被更改为公司保密)...

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
    = "{\n"
    + "    \"sandboxIndicator\": true,\n"
    + "    \"skipBadLines\": false,\n"
    + "    \"fileSeparator\": \"COMMA\",\n"
    + "    \"blockSize\": false,\n"
    + "    \"gameUUID\": \"43a004c9-2130-4e75-8fd4-e5fccae31840\",\n"
    + "    \"useFriends\": \"false\"\n"
    + "}\n"
    + "";

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

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

现在我在最后一行收到编译错误,说它无法从void转换为ClientResponse .

我之前从这篇文章得到了一些关于RestFul服务的指导..

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

2 回答

  • 9

    “现在我在最后一行收到编译错误,说它无法从void转换为ClientResponse . ”

    查看WebResource的javadoc . 看看post(Object) (with Object arg) . 它返回void .

    您需要使用重载的post(Class returnType, requestEntity),它返回 returnType 类型的实例 .

    所以你应该做的事情

    ClientResponse response = webResource
            .type(MediaType.MULTIPART_FORM_DATA_TYPE)
            .post(ClientResponse.class, multipartEntity);
    
  • 4

    按照jersey documentation,他们提供示例客户端代码 . 以下是发布多部分请求的代码段:

    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()));
    

相关问题