0

I would like to post some data to a rest api.

The API documentation (See page 38) asks for the following:

curl -u "USERNAME:PASSWORD" -H "Content-type: text/xml" -X "POST"
--data-binary @-
"https://qualysapi.qualys.com/qps/rest/3.0/create/was/webapp/" <
file.xml
Note: “file.xml” contains the request POST data.
Request POST data:
<ServiceRequest>
 <data>
 <WebApp>
 <name><![CDATA[My Web Application]]></name>
 <url><![CDATA[http://mywebapp.com]]></url>
 </WebApp>
 </data>
</ServiceRequest>

I have confirmed that the call works on the command line using curl.

I then began to write a small app in Java and found UniRest.

Thats where the problem starts. I do not know how to convert the curl request into Unirest.

I have this much so far:

Unirest.post("http://apiurl).basicAuth("user","pass").field(name, file).asBinary();

the latter half

.field(name, file).asBinary();

doesnt make sense to me. What is the intent behind giving the file a name. Isn't suppose to retrieve the data from the file?

Furthermore, I would like to avoid writing data to file. How can I create the same xml with UniRest.

If not xml, could I do the same with JSON? The API attached above (appendix C) also accepts JSON. However, how can I nest fields with the builder pattern of the Unirest api

Cripto
  • 3,581
  • 7
  • 41
  • 65

1 Answers1

1

According to the UniRest documentation, it looks like you can write any array of bytes to a field in the request. You just have to encode the string into a byte array.

Unirest.post("http://apiroot") .field(name, xmlString.getBytes(StandardCharsets.UTF_8)) .asBinary();

Alternatively, you can use any InputStream,

Unirest.post("http://apiroot") .field(name, new CharSequenceInputStream(xmlString, StandardCharsets.UTF_8)) .asBinary();

Usually data is the body of the request though (not as a field). If you do want to send the data as the request body and not a form field, you should use the body(String body) method instead of the field(String name, Object object) method, for instance:

String data = "<ServiceRequest>... etc...</ServiceRequest>"; Unirest.post("http://apiroot") .body(xmlString) .asBinary();

RudolphEst
  • 1,240
  • 13
  • 21
  • Would it then be `body(xml string)` to match the original `curl` on the command line? – Cripto Aug 19 '16 at 20:42
  • Yip, I think that will work. Since I cannot run a test case against your server API, I cannot be sure though. – RudolphEst Aug 19 '16 at 20:43
  • I will confirm later today and mark as correct if its correct. Do you mind editing your answer with the `body` method and the `xml` data from the above in the mean time? – Cripto Aug 19 '16 at 20:49