eksempel:
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
public class Login {
private HttpClient client;
public Login() {
client = new DefaultHttpClient();
}
public void login(String url, String userField, String userValue, String passField, String passValue) throws Exception {
List<NameValuePair> nvp = new ArrayList<NameValuePair>();
nvp.add(new BasicNameValuePair(userField, userValue));
nvp.add(new BasicNameValuePair(passField, passValue));
post(url, nvp);
}
public String get(String url) throws Exception {
HttpGet met = new HttpGet(url);
return EntityUtils.toString(client.execute(met).getEntity());
}
public String post(String url, List<NameValuePair> nvp) throws Exception {
HttpPost met = new HttpPost(url);
if (nvp != null) {
met.setEntity(new UrlEncodedFormEntity(nvp, HTTP.UTF_8));
}
return EntityUtils.toString(client.execute(met).getEntity());
}
public static void main(String[] args) throws Exception {
Login lgi = new Login();
lgi.get("
http://localhost:8080/login/open/test.jsp");
lgi.login("
http://localhost:8080/login/j_security_check", "j_username", "userarne", "j_password", "xxxxxx");
System.out.println(lgi.get("
http://localhost:8080/login/open/test.jsp"));
}
}