【问题标题】:Postman - Sending image file and json on POST邮递员 - 在 POST 上发送图像文件和 json
【发布时间】:2017-11-28 00:45:01
【问题描述】:

我正在使用 Postman 测试 REST Web API,并且我有一个接收此对象的方法:

public class NewShipmentDto implements Serializable {
  private String description;
  private Long senderId;
  private Long receiverId;
  private byte[] packageImage;
  private CommissionPaidBy commissionPaidBy;
  private Long senderPaymentMethod;
  private LocationDto senderLocation;
  private LocationDto receiverLocation;

// + constructors and gets/sets
}

所以我的 POST 的正文需要是这样的:

{
    "description":"Libros",
    "senderId":1,
    "receiverId":1,
    "commissionPaidBy":"BOTH",
    "senderPaymentMethod":1,
    "senderLocation":
    {
        "latitud":100,
        "longitud":100
    },
    "receiverLocation":
    {
        "latitud":100,
        "longitud":100
    }
}

但我还需要发送文件,以便将其转换为byte []。问题是如果我使用表单数据来传递文件,我该如何发送这些位:

"receiverLocation":
{
    "latitud":100,
    "longitud":100
}

是否可以在表单数据中发送嵌套的 json?

这是我的POST方法,我还没有添加读取文件的逻辑:

@POST
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response addShipment(String shipment) throws EnviosYaException {
    Gson gson = new Gson();
    NewShipmentDto newShipmentDto = gson.fromJson(shipment, NewShipmentDto.class);
    NewShipmentResponseDto response = shipmentServices.addShipment(newShipmentDto);
    return Response.ok(gson.toJson(response)).build();
}

如有必要,我可以更改 json 的结构以避免嵌套 json,但我想先知道它是否可能。 谢谢

【问题讨论】:

    标签: json web-services post jakarta-ee postman


    【解决方案1】:

    看起来您正在将 JAX-RS 用于 REST API。对于您的用例 multipart/format-data 内容类型更合适。 请看看这个JAX-RS question

    或者

    如果您希望保持 JSON 结构完整,可以将 base64 编码数据存储在图像字段的字符串中。模型看起来像。

    public class NewShipmentDto implements Serializable {
      private String description;
      private Long senderId;
      private Long receiverId;
      private String encodedPackageImage;
      private CommissionPaidBy commissionPaidBy;
      private Long senderPaymentMethod;
      private LocationDto senderLocation;
      private LocationDto receiverLocation;
    
      // + constructors and gets/sets
    }
    

    【讨论】:

      猜你喜欢
      • 2020-10-30
      • 2021-10-13
      • 2016-12-22
      • 2019-09-07
      • 2019-01-20
      • 1970-01-01
      • 1970-01-01
      • 2021-09-17
      • 1970-01-01
      相关资源
      最近更新 更多