Cannon Moyer
Cannon Moyer

Reputation: 92

POST xml string to URL with Java

I have downloaded the Apache Http Components 4.5 jars and I am trying to use this API for making a POST request to a URL that accepts xml as a SSTRING NOT A FILE. All of the examples I have found online require that you define a PostMethod object. This Object is supposed to be apart of the http components api, but the package for the PostMethod doesn't exist. I am positive that I have all of the jars added to my class path correctly. Is there any alternative I can use or is there anything I can do to fix this?

Upvotes: 0

Views: 629

Answers (1)

user3653004
user3653004

Reputation: 61

The httpcomponents project also contains a more convenient fluent API for HTTP as a separate download (fluent-hc, maven groupdId: org.apache.httpcomponents, artifactId: fluent-hc). With fluent-hc a POST with a String looks like this:

import org.apache.http.client.fluent.*;

Request post = Request.Post(url).bodyString(contentString, ContentType.APPLICATION_XML).addHeader("Accept", "application/xml");
Response resp = post.execute();
String answerContent = resp.returnContent().asString();

See https://hc.apache.org/httpcomponents-client-ga/tutorial/html/fluent.html for more.

Upvotes: 1

Related Questions