IT Certificaions

Google Cloud Platform

Wednesday, February 13, 2013

Send POST request using java.net.URLConnection and parse xml response

Send POST request on server....
-------------------------------------------------------------------

public static StringBuffer getWebServiceResponse(String urlString,
String to, String from, String subject, String mailBody) {
StringBuffer dataBuffer = new StringBuffer();
String charset = "UTF-8";

String query;
OutputStream output = null;
try {
query = String.format(
"to=%s&from=%s&subject=%s&mailBody=%s",
URLEncoder.encode(to, charset),
URLEncoder.encode(from, charset),
URLEncoder.encode(subject, charset),
URLEncoder.encode(mailBody, charset));
            log.info("query:"+query);
URLConnection connection;
if (ETradeConstants.PROXY_URL != null) {
connection = new URL("http", "10.10.10.1", 3128, urlString)
.openConnection(); // For MA local machine
} else {
connection = new URL(urlString).openConnection(); // For AppEngine
}

connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=" + charset);

output = connection.getOutputStream();
output.write(query.getBytes(charset));

InputStream response = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(
response));
String line;
while ((line = rd.readLine()) != null) {
dataBuffer.append(line);
}

} catch (UnsupportedEncodingException e) {
log.severe("UnsupportedEncodingException:" + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
log.severe("IOException:" + e.getMessage());
e.printStackTrace();
} finally {
if (output != null)
try {
output.close();
} catch (IOException logOrIgnore) {
}
}

return dataBuffer;
}
----------------------------------------------

Parse this XML response. from StringBuffer....



public static EmailResponse parseXMLResponse(StringBuffer xml) {
EmailResponse emailResponse = new EmailResponse();
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputStream is = new StringBufferInputStream(xml.toString());
Document doc = db.parse(is);
doc.getDocumentElement().normalize();
NodeList nodeLst = doc.getElementsByTagName("info");
for (int s = 0; s < nodeLst.getLength(); s++) {
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
Element fstElmnt = (Element) fstNode;
NodeList fstNmElmntLst = fstElmnt
.getElementsByTagName("result");
Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
NodeList fstNm = fstNmElmnt.getChildNodes();

emailResponse.setResult(((Node) fstNm.item(0))
.getNodeValue());
NodeList lstNmElmntLst = fstElmnt
.getElementsByTagName("error");
Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
NodeList lstNm = lstNmElmnt.getChildNodes();
String error;
if(lstNm !=null && lstNm.item(0) !=null){
error=((Node) lstNm.item(0)).getNodeValue();
}else{
error="None";
}
emailResponse.setError(error);
}
}
} catch (Exception e) {
log.severe("emailResponse:parseXMLResponse: Exception:"+ e.getMessage());
e.printStackTrace();
}
return emailResponse;
}

-----------------------------------------

Where Email response...



public class EmailResponse {
private String result;
private String error;

public EmailResponse() {

}

public String toString(){
StringBuilder builder = new StringBuilder();
builder.append("EmailResponse [result=");
builder.append(result);
builder.append(", error=");
builder.append(error);
builder.append("]");
return builder.toString();
}
public void setResult(String result) {
this.result = result;
}

public String getResult() {
return result;
}

public void setError(String error) {
this.error = error;
}

public String getError() {
return error;
}


}