01: /*
02: * Copyright 2004-2008 H2 Group. Licensed under the H2 License, Version 1.0
03: * (license2)
04: * Initial Developer: H2 Group
05: */
06: package org.h2.test.server;
07:
08: import java.io.IOException;
09: import java.io.InputStream;
10: import java.io.InputStreamReader;
11: import java.net.HttpURLConnection;
12: import java.net.URL;
13:
14: import org.h2.util.IOUtils;
15:
16: /**
17: * A simple web browser simulator.
18: */
19: public class WebClient {
20:
21: private String sessionId;
22:
23: String get(String url) throws IOException {
24: HttpURLConnection connection = (HttpURLConnection) new URL(url)
25: .openConnection();
26: connection.setRequestMethod("GET");
27: connection.setInstanceFollowRedirects(true);
28: connection.connect();
29: int code = connection.getResponseCode();
30: if (code != HttpURLConnection.HTTP_OK) {
31: throw new IOException("Result code: " + code);
32: }
33: InputStream in = connection.getInputStream();
34: String result = IOUtils.readStringAndClose(
35: new InputStreamReader(in), -1);
36: connection.disconnect();
37: return result;
38: }
39:
40: void readSessionId(String result) {
41: int idx = result.indexOf("jsessionid=");
42: String id = result.substring(idx + "jsessionid=".length());
43: for (int i = 0; i < result.length(); i++) {
44: char ch = id.charAt(i);
45: if (!Character.isLetterOrDigit(ch)) {
46: id = id.substring(0, i);
47: break;
48: }
49: }
50: this .sessionId = id;
51: }
52:
53: public String get(String url, String page) throws IOException {
54: if (sessionId != null) {
55: if (page.indexOf('?') < 0) {
56: page += "?";
57: } else {
58: page += "&";
59: }
60: page += "jsessionid=" + sessionId;
61: }
62: if (!url.endsWith("/")) {
63: url += "/";
64: }
65: url += page;
66: return get(url);
67: }
68:
69: }
|