Reputation: 195
I need to make an api call rest POST method by passing XML request body. I achieved the same through VB.net. In VB.net I used XElement
to pass request body.
For example:
Dim xml As XElement = <Request xmlns="request"><ID>181</ID><Password>String content</Password><Service>service name</Service><UserName>username</UserName></Request>.
In Java how to pass the above XML request body to call rest post method.
Upvotes: 6
Views: 33546
Reputation: 195
public static void main(String[] args) {
try {
String url = "pass your url";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type",
"application/xml;charset=utf-8");
String urlParameters = "<Request xmlns=\"abc\"><ID>1</ID><Password></Password></Request>";
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
String responseStatus = con.getResponseMessage();
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("response:" + response.toString());
}
} catch (IOException e) {
System.out.println("error" + e.getMessage());
}
}
Upvotes: 1
Reputation: 2051
This is sample code of how to do it, or you can find some Java library, such as commons-httpclient
, which would be easier than this.
String xmlString = "<?xml version='1.0' encoding='gb2312'?>"
+ "<Req>"
+ "<EventContentReq>"
+ "<EventID>101</EventID >"
+ "</EventContentReq>"
+ "</Req>";
byte[] xmlData = xmlString.getBytes();
String urlStr = "http://124.128.62.164:7001/test";
DataInputStream input = null;
java.io.ByteArrayOutputStream out = null;
try {
URL url = new URL(urlStr);
URLConnection urlCon = url.openConnection();
urlCon.setDoOutput(true);
urlCon.setDoInput(true);
urlCon.setUseCaches(false);
urlCon.setRequestProperty("Content-Type", "text/xml");
urlCon.setRequestProperty("Content-length", String.valueOf(xmlData.length));
input = new DataInputStream(urlCon.getInputStream());
out = new java.io.ByteArrayOutputStream();
byte[] bufferByte = new byte[256];
int l = -1;
while ((l = input.read(bufferByte)) > -1) {
out.write(bufferByte, 0, l);
out.flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
input.close();
} catch (Exception ex) {
}
}
Upvotes: 2