Sending GET Requests with XML Parameters in Java
Using HttpURLConnection
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
public class XmlClient {
public static Document fetchXml(String endpoint, String xmlPayload) throws Exception {
URL targetUrl = new URL(endpoint);
HttpURLConnection connection = (HttpURLConnection) targetUrl.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
String encodedPayload = URLEncoder.encode(xmlPayload, "UTF-8");
connection.getOutputStream().write(encodedPayload.getBytes("UTF-8"));
int statusCode = connection.getResponseCode();
if (statusCode != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("HTTP error: " + statusCode);
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream())
);
StringBuilder responseBody = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
responseBody.append(line);
}
reader.close();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document document = factory.newDocumentBuilder()
.parse(new InputSource(new StringReader(responseBody.toString())));
return document;
}
}
Using Apache HttpClient
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import java.io.StringReader;
public class XmlHttpClient {
public static Document fetchXmlDocument(String baseUrl, String xmlPayload) throws Exception {
try (CloseableHttpClient client = HttpClients.createDefault()) {
String encodedPayload = URLEncoder.encode(xmlPayload, "UTF-8");
HttpGet request = new HttpGet(baseUrl + "?data=" + encodedPayload);
request.setHeader("Accept", "application/xml");
var response = client.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
throw new RuntimeException("Request failed with status: " + statusCode);
}
String xmlResponse = EntityUtils.toString(response.getEntity());
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
return factory.newDocumentBuilder()
.parse(new InputSource(new StringReader(xmlResponse)));
}
}
}
Returning Raw XML String
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
public class XmlStringClient {
public static String fetchXmlString(String url, String payload) throws Exception {
try (CloseableHttpClient client = HttpClients.createDefault()) {
String encoded = URLEncoder.encode(payload, StandardCharsets.UTF_8)
.replace("+", "%20");
HttpGet getRequest = new HttpGet(url + "?xml=" + encoded);
var response = client.execute(getRequest);
return EntityUtils.toString(response.getEntity());
}
}
}
Using POST for XML Payloads
When XML payloads are large or contain special characters, switching to POST may be more appropriate:
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.nio.charset.StandardCharsets;
public class XmlPostClient {
public static String postXml(String endpoint, String xmlBody) throws Exception {
try (CloseableHttpClient client = HttpClients.createDefault()) {
HttpPost post = new HttpPost(endpoint);
post.setEntity(new StringEntity(xmlBody, StandardCharsets.UTF_8));
post.setHeader("Content-Type", "text/xml; charset=UTF-8");
var response = client.execute(post);
return EntityUtils.toString(response.getEntity());
}
}
}
Key Considerations
URL Encoding: When appending XML data to query parameters, proper URL encoding is essential. Special characters like <, >, and & must be encoded to prevent malformed requests. Use URLEncoder with UTF-8 charset and handle the space-to-plus conversion.
Character Limits: GET requests have URL length restrictions (typically 2048 characters). For larger XML payloads, considre POST or include the XML in request headers instead.
XML Parsing: After receiving the response, parse using DocumentBuilder for DOM manipulation, or use streaming parsers like SAX or StAX for memory-efficient processing of large documents.
Content-Type Headers: Set appropriate Accept and Content-Type headers based on server requirements. Common values include application/xml, text/xml, and text/plain.