Skip to content

Instantly share code, notes, and snippets.

@benelog
Created January 6, 2012 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benelog/1569764 to your computer and use it in GitHub Desktop.
Save benelog/1569764 to your computer and use it in GitHub Desktop.
HttpUnit
/*
* @(#)NaverWebClient.java 1.0 2011. 7. 15
*/
package testsupport;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.Cookie;
import org.xml.sax.SAXException;
import com.meterware.httpunit.GetMethodWebRequest;
import com.meterware.httpunit.HttpUnitOptions;
import com.meterware.httpunit.WebClient;
import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebResponse;
/**
* @author benelog
*/
public class NaverWebClient {
static final String LOGIN_URL = "http://static.nid.naver.com/login.nhn";
public List<Cookie> getCookiesAfterLogin(String id, String pw) throws IOException, SAXException {
WebClient client = login(id, pw);
return collectCookies(client);
}
public String getCookieHeaderAfterLogin(String id, String pw) throws IOException, SAXException {
List<Cookie> cookies = getCookiesAfterLogin(id, pw);
StringBuilder cookiesHeader = new StringBuilder();
for (Cookie cookie : cookies) {
cookiesHeader.append(String.format("%s=%s; ", cookie.getName(), cookie.getValue()));
}
return cookiesHeader.toString();
}
private List<Cookie> collectCookies(WebClient webClient) {
List<Cookie> cookies = new ArrayList<Cookie>();
String[] cookieNames = webClient.getCookieNames();
for (String name : cookieNames) {
String value = webClient.getCookieValue(name);
cookies.add(new Cookie(name, value));
}
return cookies;
}
private WebClient login(String id, String pw) throws IOException, SAXException {
HttpUnitOptions.setScriptingEnabled(false);
WebConversation conv = new WebConversation();
GetMethodWebRequest request = new GetMethodWebRequest(LOGIN_URL);
WebResponse loginFormRes = conv.getResource(request);
WebForm form = loginFormRes.getFormWithName("frmNIDLogin");
form.setParameter("id", id);
form.setParameter("pw", pw);
WebResponse res = form.submit();
return res.getClient();
}
}
<dependency>
<groupId>rhino</groupId>
<artifactId>js</artifactId>
<version>1.6R5</version>
</dependency>
<dependency>
<groupId>httpunit</groupId>
<artifactId>httpunit</artifactId>
<version>1.7</version>
<scope>test</scope>
</dependency>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment