我需要为通过curl传入一些参数的工作更新shell脚本,如下所示
curl -X POST -H 'Content-Type: application/json' "http://myurl?param1=test1¶m2=test2¶m3=test3"
这一切都很好,但问题是我的api需要第四个参数,它不仅仅是一个字符串,而是在api中定义的java对象。有什么我可以用shell脚本来处理的吗?谢谢你的帮助。我对java还比较陌生,所以有点挣扎。
wdebmtf21#
有两种可能的选择,还有很多。
发送序列化 Object 至 byte[] .编码到 base64 .
Object
byte[]
base64
ByteArrayOutputStream bos= new ByteArrayOutputStream(); ObjectOutputStream obs = new ObjectOutputStream(bos); obs.writeObject(yourJavaObject); obs.flush(); curlStringObj= new String(Base64.encode(bos.toByteArray()));
这个 curlStringObj 字符串应该是您在curl调用中发送的字符串。接收解码自 base64 反序列化 byte[] 至 Object ```byte b[] = Base64.decode(curlStringObj.getBytes());ByteArrayInputStream bis= new ByteArrayInputStream(b);ObjectInputStream ois = new ObjectInputStream(bis);YourJavaObject receivedJavaObject= (YourJavaObject) ois.readObject();
curlStringObj
### gson(json) 另一个选择是将其序列化为json,例如,使用gson lib。可能是最简单的方法之一。 发送
Gson gson = new Gson();String curlStringObj = gson.toJson(yourJavaObject);
接收
Gson gson = new Gson();YourJavaObject jObject = gson.fromJson(curlStringObj ,YourJavaObject.class);
不管怎样,就拿这些作为例子吧。首先检查api的规范并根据它转换对象。希望能有所帮助。
1条答案
按热度按时间wdebmtf21#
有两种可能的选择,还有很多。
base64+字节[]
发送
序列化
Object
至byte[]
.编码到
base64
.这个
curlStringObj
字符串应该是您在curl调用中发送的字符串。接收
解码自
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 gson = new Gson();
String curlStringObj = gson.toJson(yourJavaObject);
Gson gson = new Gson();
YourJavaObject jObject = gson.fromJson(curlStringObj ,YourJavaObject.class);