Monday, July 13, 2015

Web Services connection - cookie value retrieval and resubmission

package [COMPANY NAME];

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom2.*;
import org.jdom2.input.SAXBuilder;

public class WebServiceHelper {

private final String USER_AGENT = "Mozilla/5.0";
private static Log log = LogFactory.getLog(WebServiceHelper.class);


/**
     * Login Form
     * @param username
     * @param password
     * @param entityId
     * @return
     */
    public LoginToken login( String username, String password, String entityId) {
   
    LoginToken token = new LoginToken();
   
try {
URL url = new URL("REST-URL");

HttpURLConnection con = (HttpURLConnection) url.openConnection();

//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

String urlParameters = "UserName=" + username + "&Password=" + password + "&EntityID=" + entityId;

// Send post request
con.setDoOutput(true);

DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();

con.connect();

// retrieves the cookie from the response header
token.setCookie(con.getHeaderField("Set-Cookie"));

SAXBuilder builder = new SAXBuilder();
Document xmlDocument;

xmlDocument = builder.build(con.getInputStream());
xmlDocument.setDocType(new DocType("xml"));
Element rss = xmlDocument.getRootElement();

// retrieves the currentUserID from the xml response
token.setGuID(rss.getChild("Data").getChildText("Message").split("\\|")[1]);


} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}

return token;

}
   
   
   
    public Element callService( String urlString, String method, String urlParameters, LoginToken token ) {
   
    Element element = null;
   
try {
URL url = new URL(urlString);

HttpURLConnection con = (HttpURLConnection) url.openConnection();

//add reuqest header
con.setRequestMethod(method);
con.setRequestProperty("Cookie", token.getCookie());
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

// Send post request
con.setDoOutput(true);

// USE THIS ONLY ON POST METHODS
if ( method.toUpperCase().equals("POST")) {
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
}

con.connect();

SAXBuilder builder = new SAXBuilder();
Document xmlDocument;

int status = con.getResponseCode();
log.info("Response Code: " + status);

// MAKE SURE THE RESPONSE CODE IS VALID, AKA 200.
if ( status == 200 ) {
xmlDocument = builder.build(con.getInputStream());
xmlDocument.setDocType(new DocType("xml"));
element = xmlDocument.getRootElement();
} else if ( status == 404 ) {
log.info("404 ERROR: IF YOU'RE MAKING A GET CALL. MAKE SURE YOU'RE NOT WRITING OUTPUT");
}


} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}

return element;

}
   


public static void printOutElements(Element current, int depth) {
   printSpaces(depth);
   if ( null != current ) {
   System.out.println(current.getName() + " " + current.getValue());
   List children = current.getChildren();
   Iterator iterator = children.iterator();
   while (iterator.hasNext()) {
     Element child = (Element) iterator.next();
     printOutElements(child, depth+1);
   }
   }
 
 }

private static void printSpaces(int n) {
 
   for (int i = 0; i < n; i++) {
     System.out.print(' ');
   }
 
 }
 
   

   

}

No comments:

Post a Comment