I have a XML like below which is stored as a String in xmlData
variable and I need to pass this String to my url in client_data
variable -
<?xml version="1.0"?>
<ClientData
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.google.com model.xsd"
xmlns="http://www.google.com">
<client id="100">
<clock>
<for>
<etc>val(tery) = 1</etc>
<while><![CDATA[val(tery) < 20]]></while>
</for>
</clock>
</model>
</ClientData>
Below is the URL I am hitting on the browser by URL encoding client_data
value to get the response back and it works fine.
http://localhost:8080/test_tmp?max_time=30&users=1000&client_data=<?xml version="1.0"?>
<ClientData
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.google.com model.xsd"
xmlns="http://www.google.com">
<client id="100">
<clock>
<for>
<etc>val(tery) = 1</etc>
<while><![CDATA[val(tery) < 20]]></while>
</for>
</clock>
</model>
</ClientData>
Now I need to do the same thing through Apache HttpClient
. What is the best way to do this?
I have got below code but not sure whethere there is any better way to do this? Is there anything I can improve on or some better way of doing it?
public static void main(String[] args) {
String xmlData = getXMLData();
String url = generateURL(xmlData);
HttpClient httpclient = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
HttpResponse httpResponse = httpclient.execute(request);
BufferedReader rd = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
StringBuffer response = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
response.append(line);
}
// prints response
System.out.println(response);
}
private static String generateURL(final String clientData) {
StringBuilder url = new StringBuilder();
url.append("http://localhost:8080/test_tmp?max_time=30&users=1000&client_data=");
url.append(URLEncoder.encode(clientData, "UTF-8"));
return url.toString();
}
Honestly, I don't think you want to try and pass XML through your URI. There are several things to consider. One, some servers will block long URIs (Google first result: http://www.checkupdown.com/status/E414.html ). Next, you would want to "encode" the URI so it escapes all of your chars that are not ready to be passed raw.
Consider doing a "POST" with the xml the body of the HTTP message.
Hope this helps.