通过curl将java对象传递到url中



我需要为通过curl传递一些参数的工作更新一个shell脚本,比如

curl -X POST -H 'Content-Type: application/json' "http://myurl?param1=test1&param2=test2&param3=test3"

这一切都很好,但问题是我的API需要第四个参数,它不仅仅是字符串,而是在API中定义的Java对象。有什么是我可以用shell脚本管理的吗?感谢您的帮助。我是Java的新手,所以我有点不知所措。

在许多其他选项中,有两个可能的选项。


Base64 + byte[]

  1. 发送

    • 串行化Objectbyte[]

    • 编码为base64

      ByteArrayOutputStream bos= new ByteArrayOutputStream();
      ObjectOutputStream obs = new ObjectOutputStream(bos);
      obs.writeObject(yourJavaObject);
      obs.flush();
      curlStringObj= new String(Base64.encode(bos.toByteArray()));       
      

curlStringObj字符串应该是您在curl调用中发送的字符串。

  1. 接收

    • base64解码

    • byte[]反序列化Object

      byte b[] = Base64.decode(curlStringObj.getBytes()); 
      ByteArrayInputStream bis= new ByteArrayInputStream(b);
      ObjectInputStream ois = new ObjectInputStream(bis);
      YourJavaObject receivedJavaObject= (YourJavaObject) ois.readObject();
      

GSON (Json)

另一种选择是将其序列化为JSON,例如,使用GSONlib。可能是最简单的方法之一。

  1. 发送

    Gson gson = new Gson();
    String curlStringObj = gson.toJson(yourJavaObject);
    
  2. 接收

    Gson gson = new Gson(); 
    YourJavaObject jObject = gson.fromJson(curlStringObj ,YourJavaObject.class);
    

无论如何,只是以这些为例。首先检查API的规范,并根据该规范转换对象。希望它能有所帮助。

最新更新