1. I chose to use Apache HttpComponents.
2. Download the latest HttpClient jars from https://hc.apache.org/downloads.cgi
3. In my servlet, I import the following classes.
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
4. In the doPost method, I add the following code.
// HTTP post xml document to outside service
HttpPost post = new HttpPost("https://testserviceurl");
post.setHeader("Content-Type", "application/xml");
post.setEntity(new StringEntity(xmlString));
HttpClient client = HttpClientBuilder.create().build();
HttpResponse resp = client.execute(post);
String result = EntityUtils.toString(resp.getEntity());
System.out.println("post result:" + result);
HttpClient really provides a simply way to do the job.
No comments:
Post a Comment