Cripto
Cripto

Reputation: 3751

Converting Curl to POST api for java

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

Upvotes: 0

Views: 1397

Answers (1)

RudolphEst
RudolphEst

Reputation: 1250

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

Upvotes: 1

Related Questions