Here is a simple example to illustrate it:
package Testing;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jetty.client.ContentExchange;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.HttpExchange;
import org.eclipse.jetty.io.Buffer;
public class JettyHttpClientCookieTest {
public final static void main(String[] args) throws Exception {
String loginUri = new String("https://10.176.40.10:8443/admin?op=login&username=<username>&password=<password>");
String setGroupUri = new String("https://10.176.40.10:8443/admin?op=setGroup&groupId=1");
if (httpClient == null) {
httpClient = new HttpClient();
}
httpClient.setConnectorType(HttpClient.CONNECTOR_SELECT_CHANNEL);
try {
System.out.println("Start the Http client...");
httpClient.start();
System.out.println("Login to CMS ...");
ContentExchange exchange = new ContentExchange(true) {
protected void onResponseHeader(Buffer name, Buffer value) throws IOException {
System.out.println("Buffer name: " + name.toString() + "; Buffer value: " + value.toString());
if (name.toString().equals("Set-Cookie")) {
cookies.add(value.toString());
}
}
};
exchange.setMethod("POST");
exchange.setURL(loginUri);
httpClient.send(exchange);
if (exchange.waitForDone() == ContentExchange.STATUS_COMPLETED) {
System.out.println("ContentExchange content: " + exchange.getResponseContent());
}
System.out.println("Set the group");
ContentExchange exchange2 = new ContentExchange(true);
exchange2.setMethod("POST");
exchange2.setURL(setGroupUri);
for (String cookie: cookies) {
exchange2.setRequestHeader("Cookie", cookie);
}
httpClient.send(exchange2);
if (exchange2.waitForDone() == ContentExchange.STATUS_COMPLETED) {
System.out.println("ContentExchange content: " + exchange2.getResponseContent());
}
System.out.println("Fetch Shefl...");
ContentExchange exchange3 = new ContentExchange(true);
String fetchShelfUri = new String("https://10.176.40.10:8443/fetch?shelf");
exchange3.setMethod("GET");
exchange3.setURL(fetchShelfUri);
for (String cookie: cookies) {
exchange3.setRequestHeader("Cookie", cookie);
}
httpClient.send(exchange3);
if (exchange3.waitForDone() == ContentExchange.STATUS_COMPLETED) {
System.out.println("ContentExchange content: " + exchange3.getResponseContent());
}
System.out.println("Done");
}
catch (Exception e) {
return;
}
}
public static class JettyHttpExchangeExt extends HttpExchange {
// Examine the response header
protected void onResponseHeader(Buffer name, Buffer value) throws IOException {
System.out.println("Buffer name: " + name.toString() + "; Buffer value: " + value.toString());
}
}
public static List<String> cookies = new ArrayList<String>();
public static HttpClient httpClient = null;
}