Arvind Arvind - 2 years ago 67
Java Question

How to make GET and POST request from servlet with content type and content

I want to make GET and POST requests from a servlet to another server, where I will be sending XML content and a Content-type header.

However, there is no method in HTTPRequest to set Content-type and content.

How can I do that?

Answer Source

Using HTTPUrlConnection this can be approached as follows:

connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type", "text/xml");

I personally prefer the to use the Apache Http Client. The Apache HTTP client "post xml" example demonstrates you how to post an xml and correctly set's the posted entities mimetype and encoding.

Apache HTTP Client Post XML Example

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download