How to use Session class of org.openqa.selenium.grid.graphql package

Best Selenium code snippet using org.openqa.selenium.grid.graphql.Session

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1// Licensed to the Software Freedom Conservancy (SFC) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The SFC licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18package org.openqa.selenium.grid.graphql;
19
20import com.google.common.collect.ImmutableList;
21import org.openqa.selenium.Capabilities;
22import org.openqa.selenium.grid.data.Availability;
23import org.openqa.selenium.grid.data.NodeId;
24import org.openqa.selenium.grid.data.Session;
25import org.openqa.selenium.grid.data.Slot;
26import org.openqa.selenium.internal.Require;
27import org.openqa.selenium.json.Json;
28
29import java.net.URI;
30import java.util.ArrayList;
31import java.util.HashMap;
32import java.util.List;
33import java.util.Map;
34
35public class Node {
36
37  private static final Json JSON = new Json();
38  private final NodeId id;
39  private final URI uri;
40  private final Availability status;
41  private final int maxSession;
42  private final Map<Capabilities, Integer> stereotypes;
43  private final Map<Session, Slot> activeSessions;
44  private final String version;
45  private final OsInfo osInfo;
46  private final int slotCount;
47
48
49  public Node(NodeId id,
50              URI uri,
51              Availability status,
52              int maxSession,
53              int slotCount,
54              Map<Capabilities, Integer> stereotypes,
55              Map<Session, Slot> activeSessions,
56              String version,
57              OsInfo osInfo) {
58    this.id = Require.nonNull("Node id", id);
59    this.uri = Require.nonNull("Node uri", uri);
60    this.status = status;
61    this.maxSession = maxSession;
62    this.slotCount = slotCount;
63    this.stereotypes = Require.nonNull("Node stereotypes", stereotypes);
64    this.activeSessions = Require.nonNull("Active sessions", activeSessions);
65    this.version = Require.nonNull("Grid Node version", version);
66    this.osInfo = Require.nonNull("Grid Node OS info", osInfo);
67  }
68
69  public List<org.openqa.selenium.grid.graphql.Session> getSessions() {
70    return activeSessions.entrySet().stream()
71      .map(this::createGraphqlSession)
72      .collect(ImmutableList.toImmutableList());
73  }
74
75  public int getSlotCount() {
76    return slotCount;
77  }
78
79  public int getSessionCount() {
80    return activeSessions.size();
81  }
82
83  public NodeId getId() {
84    return id;
85  }
86
87  public URI getUri() {
88    return uri;
89  }
90
91  public int getMaxSession() {
92    return maxSession;
93  }
94
95  public List<String> getActiveSessionIds() {
96    return activeSessions.keySet().stream().map(session -> session.getId().toString())
97      .collect(ImmutableList.toImmutableList());
98  }
99
100  public String getStereotypes() {
101    List<Map<String, Object>> toReturn = new ArrayList<>();
102
103    for (Map.Entry<Capabilities, Integer> entry : stereotypes.entrySet()) {
104      Map<String, Object> details = new HashMap<>();
105      details.put("stereotype", entry.getKey());
106      details.put("slots", entry.getValue());
107      toReturn.add(details);
108    }
109
110    return JSON.toJson(toReturn);
111  }
112
113  public Availability getStatus() {
114    return status;
115  }
116
117  public String getVersion() {
118    return version;
119  }
120
121  public OsInfo getOsInfo() {
122    return osInfo;
123  }
124
125  private org.openqa.selenium.grid.graphql.Session createGraphqlSession(
126    Map.Entry<Session, Slot> entry) {
127    Session session = entry.getKey();
128    Slot slot = entry.getValue();
129
130    return new org.openqa.selenium.grid.graphql.Session(
131      session.getId().toString(),
132      session.getCapabilities(),
133      session.getStartTime(),
134      session.getUri(),
135      id.toString(),
136      uri,
137      slot
138    );
139  }
140}
141
Full Screen
copy
1// Licensed to the Software Freedom Conservancy (SFC) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The SFC licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18package org.openqa.selenium.grid.graphql;
19
20import org.openqa.selenium.Capabilities;
21import org.openqa.selenium.grid.data.Slot;
22import org.openqa.selenium.internal.Require;
23import org.openqa.selenium.json.Json;
24
25import java.net.URI;
26import java.time.Duration;
27import java.time.Instant;
28import java.time.ZoneId;
29import java.time.format.DateTimeFormatter;
30
31public class Session {
32
33  private static final DateTimeFormatter DATE_TIME_FORMATTER =
34      DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss").withZone(ZoneId.systemDefault());
35
36  private final String id;
37  private final Capabilities capabilities;
38  private final Instant startTime;
39  private final URI uri;
40  private final String nodeId;
41  private final URI nodeUri;
42  private final Slot slot;
43  private static final Json JSON = new Json();
44
45  public Session(String id, Capabilities capabilities, Instant startTime, URI uri, String nodeId,
46                 URI nodeUri, Slot slot) {
47    this.id = Require.nonNull("Session id", id);
48    this.capabilities = Require.nonNull("Session capabilities", capabilities);
49    this.startTime = Require.nonNull("Session Start time", startTime);
50    this.uri = Require.nonNull("Session uri", uri);
51    this.nodeId = Require.nonNull("Node id", nodeId);
52    this.nodeUri = Require.nonNull("Node uri", nodeUri);
53    this.slot = Require.nonNull("Slot", slot);
54  }
55
56  public String getId() {
57    return id;
58  }
59
60  public String getCapabilities() {
61    return JSON.toJson(capabilities);
62  }
63
64  public String getStartTime() {
65    return DATE_TIME_FORMATTER.format(startTime);
66  }
67
68  public URI getUri() {
69    return uri;
70  }
71
72  public String getNodeId() {
73    return nodeId;
74  }
75
76  public URI getNodeUri() {
77    return nodeUri;
78  }
79
80  public String getSessionDurationMillis() {
81    long duration = Duration.between(startTime, Instant.now()).toMillis();
82    return String.valueOf(duration);
83  }
84
85  public org.openqa.selenium.grid.graphql.Slot getSlot() {
86    return new org.openqa.selenium.grid.graphql.Slot(
87        slot.getId().getSlotId(),
88        slot.getStereotype(),
89        slot.getLastStarted());
90  }
91
92}
93
Full Screen
copy
1var uri = URI.create("https://httpbin.org/get?age=26&isHappy=true");
2var client = HttpClient.newHttpClient();
3var request = HttpRequest
4        .newBuilder()
5        .uri(uri)
6        .header("accept", "application/json")
7        .GET()
8        .build();
9var response = client.send(request, HttpResponse.BodyHandlers.ofString());
10System.out.println(response.statusCode());
11System.out.println(response.body());
12
Full Screen
copy
1var responseAsync = client
2        .sendAsync(request, HttpResponse.BodyHandlers.ofString())
3        .thenApply(HttpResponse::body)
4        .thenAccept(System.out::println);
5// responseAsync.join(); // Wait for completion
6
Full Screen
copy
1var request = HttpRequest
2        .newBuilder()
3        .uri(uri)
4        .version(HttpClient.Version.HTTP_2)
5        .timeout(Duration.ofMinutes(1))
6        .header("Content-Type", "application/json")
7        .header("Authorization", "Bearer fake")
8        .POST(BodyPublishers.ofString("{ title: 'This is cool' }"))
9        .build();
10var response = client.send(request, HttpResponse.BodyHandlers.ofString());
11
Full Screen
copy
1String html = new JdkRequest("http://www.google.com").fetch().body();
2
Full Screen
copy
1OkHttpClient client = new OkHttpClient();
2
Full Screen
copy
1Request request = new Request.Builder()
2      .url(url)
3      .build();
4
Full Screen
copy
1Response response = client.newCall(request).execute();
2
Full Screen
copy
1package org.boon.utils;
2
3import java.io.IOException;
4import java.io.InputStream;
5import java.net.HttpURLConnection;
6import java.net.URL;
7import java.net.URLConnection;
8import java.util.Map;
9
10import static org.boon.utils.IO.read;
11
12public class HTTP {
13
Full Screen
copy
1public static String get(
2        final String url) {
3
4    Exceptions.tryIt(() -> {
5        URLConnection connection;
6        connection = doGet(url, null, null, null);
7        return extractResponseString(connection);
8    });
9    return null;
10}
11
12public static String getWithHeaders(
13        final String url,
14        final Map<String, ? extends Object> headers) {
15    URLConnection connection;
16    try {
17        connection = doGet(url, headers, null, null);
18        return extractResponseString(connection);
19    } catch (Exception ex) {
20        Exceptions.handle(ex);
21        return null;
22    }
23}
24
25public static String getWithContentType(
26        final String url,
27        final Map<String, ? extends Object> headers,
28        String contentType) {
29    URLConnection connection;
30    try {
31        connection = doGet(url, headers, contentType, null);
32        return extractResponseString(connection);
33    } catch (Exception ex) {
34        Exceptions.handle(ex);
35        return null;
36    }
37}
38public static String getWithCharSet(
39        final String url,
40        final Map<String, ? extends Object> headers,
41        String contentType,
42        String charSet) {
43    URLConnection connection;
44    try {
45        connection = doGet(url, headers, contentType, charSet);
46        return extractResponseString(connection);
47    } catch (Exception ex) {
48        Exceptions.handle(ex);
49        return null;
50    }
51}
52
Full Screen
copy
1public static String postBody(
2        final String url,
3        final String body) {
4    URLConnection connection;
5    try {
6        connection = doPost(url, null, "text/plain", null, body);
7        return extractResponseString(connection);
8    } catch (Exception ex) {
9        Exceptions.handle(ex);
10        return null;
11    }
12}
13
14public static String postBodyWithHeaders(
15        final String url,
16        final Map<String, ? extends Object> headers,
17        final String body) {
18    URLConnection connection;
19    try {
20        connection = doPost(url, headers, "text/plain", null, body);
21        return extractResponseString(connection);
22    } catch (Exception ex) {
23        Exceptions.handle(ex);
24        return null;
25    }
26}
27
28
29public static String postBodyWithContentType(
30        final String url,
31        final Map<String, ? extends Object> headers,
32        final String contentType,
33        final String body) {
34
35    URLConnection connection;
36    try {
37        connection = doPost(url, headers, contentType, null, body);
38
39        return extractResponseString(connection);
40
41    } catch (Exception ex) {
42        Exceptions.handle(ex);
43        return null;
44    }
45
46}
47
48
49public static String postBodyWithCharset(
50        final String url,
51        final Map<String, ? extends Object> headers,
52        final String contentType,
53        final String charSet,
54        final String body) {
55
56    URLConnection connection;
57    try {
58        connection = doPost(url, headers, contentType, charSet, body);
59
60        return extractResponseString(connection);
61
62    } catch (Exception ex) {
63        Exceptions.handle(ex);
64        return null;
65    }
66}
67
68private static URLConnection doPost(String url, Map<String, ? extends Object> headers,
69                                    String contentType, String charset, String body
70                                    ) throws IOException {
71    URLConnection connection;/* Handle output. */
72    connection = new URL(url).openConnection();
73    connection.setDoOutput(true);
74    manageContentTypeHeaders(contentType, charset, connection);
75
76    manageHeaders(headers, connection);
77
78    IO.write(connection.getOutputStream(), body, IO.CHARSET);
79    return connection;
80}
81
82private static void manageHeaders(Map<String, ? extends Object> headers, URLConnection connection) {
83    if (headers != null) {
84        for (Map.Entry<String, ? extends Object> entry : headers.entrySet()) {
85            connection.setRequestProperty(entry.getKey(), entry.getValue().toString());
86        }
87    }
88}
89
90private static void manageContentTypeHeaders(String contentType, String charset, URLConnection connection) {
91    connection.setRequestProperty("Accept-Charset", charset == null ? IO.CHARSET : charset);
92    if (contentType!=null && !contentType.isEmpty()) {
93        connection.setRequestProperty("Content-Type", contentType);
94    }
95}
96
97private static URLConnection doGet(String url, Map<String, ? extends Object> headers,
98                                    String contentType, String charset) throws IOException {
99    URLConnection connection;/* Handle output. */
100    connection = new URL(url).openConnection();
101    manageContentTypeHeaders(contentType, charset, connection);
102
103    manageHeaders(headers, connection);
104
105    return connection;
106}
107
108private static String extractResponseString(URLConnection connection) throws IOException {
109/* Handle input. */
110    HttpURLConnection http = (HttpURLConnection)connection;
111    int status = http.getResponseCode();
112    String charset = getCharset(connection.getHeaderField("Content-Type"));
113
114    if (status==200) {
115        return readResponseBody(http, charset);
116    } else {
117        return readErrorResponseBody(http, status, charset);
118    }
119}
120
121private static String readErrorResponseBody(HttpURLConnection http, int status, String charset) {
122    InputStream errorStream = http.getErrorStream();
123    if ( errorStream!=null ) {
124        String error = charset== null ? read( errorStream ) :
125            read( errorStream, charset );
126        throw new RuntimeException("STATUS CODE =" + status + "\n\n" + error);
127    } else {
128        throw new RuntimeException("STATUS CODE =" + status);
129    }
130}
131
132private static String readResponseBody(HttpURLConnection http, String charset) throws IOException {
133    if (charset != null) {
134        return read(http.getInputStream(), charset);
135    } else {
136        return read(http.getInputStream());
137    }
138}
139
140private static String getCharset(String contentType) {
141    if (contentType==null)  {
142        return null;
143    }
144    String charset = null;
145    for (String param : contentType.replace(" ", "").split(";")) {
146        if (param.startsWith("charset=")) {
147            charset = param.split("=", 2)[1];
148            break;
149        }
150    }
151    charset = charset == null ? IO.CHARSET : charset;
152
153    return charset;
154}
155
Full Screen
copy
1static class MyHandler implements HttpHandler {
2    public void handle(HttpExchange t) throws IOException {
3
4        InputStream requestBody = t.getRequestBody();
5        String body = IO.read(requestBody);
6        Headers requestHeaders = t.getRequestHeaders();
7        body = body + "\n" + copy(requestHeaders).toString();
8        t.sendResponseHeaders(200, body.length());
9        OutputStream os = t.getResponseBody();
10        os.write(body.getBytes());
11        os.close();
12    }
13}
14
15
16@Test
17public void testHappy() throws Exception {
18
19    HttpServer server = HttpServer.create(new InetSocketAddress(9212), 0);
20    server.createContext("/test", new MyHandler());
21    server.setExecutor(null); // creates a default executor
22    server.start();
23
24    Thread.sleep(10);
25
26    Map<String,String> headers = map("foo", "bar", "fun", "sun");
27
28    String response = HTTP.postBodyWithContentType("http://localhost:9212/test", headers, "text/plain", "hi mom");
29
30    System.out.println(response);
31
32    assertTrue(response.contains("hi mom"));
33    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));
34
35    response = HTTP.postBodyWithCharset("http://localhost:9212/test", headers, "text/plain", "UTF-8", "hi mom");
36
37    System.out.println(response);
38
39    assertTrue(response.contains("hi mom"));
40    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));
41
42    response = HTTP.postBodyWithHeaders("http://localhost:9212/test", headers, "hi mom");
43
44    System.out.println(response);
45
46    assertTrue(response.contains("hi mom"));
47    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));
48
49    response = HTTP.get("http://localhost:9212/test");
50
51    System.out.println(response);
52
53    response = HTTP.getWithHeaders("http://localhost:9212/test", headers);
54
55    System.out.println(response);
56
57    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));
58
59    response = HTTP.getWithContentType("http://localhost:9212/test", headers, "text/plain");
60
61    System.out.println(response);
62
63    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));
64
65    response = HTTP.getWithCharSet("http://localhost:9212/test", headers, "text/plain", "UTF-8");
66
67    System.out.println(response);
68
69    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));
70
71    Thread.sleep(10);
72
73    server.stop(0);
74}
75
76@Test
77public void testPostBody() throws Exception {
78
79    HttpServer server = HttpServer.create(new InetSocketAddress(9220), 0);
80    server.createContext("/test", new MyHandler());
81    server.setExecutor(null); // creates a default executor
82    server.start();
83
84    Thread.sleep(10);
85
86    Map<String,String> headers = map("foo", "bar", "fun", "sun");
87
88    String response = HTTP.postBody("http://localhost:9220/test", "hi mom");
89
90    assertTrue(response.contains("hi mom"));
91
92    Thread.sleep(10);
93
94    server.stop(0);
95}
96
97@Test(expected = RuntimeException.class)
98public void testSad() throws Exception {
99
100    HttpServer server = HttpServer.create(new InetSocketAddress(9213), 0);
101    server.createContext("/test", new MyHandler());
102    server.setExecutor(null); // creates a default executor
103    server.start();
104
105    Thread.sleep(10);
106
107    Map<String,String> headers = map("foo", "bar", "fun", "sun");
108
109    String response = HTTP.postBodyWithContentType("http://localhost:9213/foo", headers, "text/plain", "hi mom");
110
111    System.out.println(response);
112
113    assertTrue(response.contains("hi mom"));
114    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));
115
116    Thread.sleep(10);
117
118    server.stop(0);
119}
120
Full Screen
copy
1HttpURLConnection.setFollowRedirects(true); // Defaults to true
2
3String url = "https://name_of_the_url";
4URL request_url = new URL(url);
5HttpURLConnection http_conn = (HttpURLConnection)request_url.openConnection();
6http_conn.setConnectTimeout(100000);
7http_conn.setReadTimeout(100000);
8http_conn.setInstanceFollowRedirects(true);
9System.out.println(String.valueOf(http_conn.getResponseCode()));
10
Full Screen
copy
1HttpURLConnection.setFollowRedirects(true); // Defaults to true
2
3String url = "https://name_of_the_url"
4URL request_url = new URL(url);
5HttpURLConnection http_conn = (HttpURLConnection)request_url.openConnection();
6http_conn.setConnectTimeout(100000);
7http_conn.setReadTimeout(100000);
8http_conn.setInstanceFollowRedirects(true);
9http_conn.setDoOutput(true);
10PrintWriter out = new PrintWriter(http_conn.getOutputStream());
11if (urlparameter != null) {
12   out.println(urlparameter);
13}
14out.close();
15out = null;
16System.out.println(String.valueOf(http_conn.getResponseCode()));
17
Full Screen
copy
1// GET
2HttpResponse response = HttpRequest
3    .create(new URI("http://www.stackoverflow.com"))
4    .headers("Foo", "foovalue", "Bar", "barvalue")
5    .GET()
6    .response();
7
Full Screen
copy
1int statusCode = response.statusCode();
2String responseBody = response.body(HttpResponse.asString());
3
Full Screen
copy
1module com.foo.bar {
2    requires jdk.incubator.httpclient;
3}
4
Full Screen
copy
1// GET http://google.com?q=baseball%20gloves&size=100
2String response = HttpRequest.get("http://google.com", true, "q", "baseball gloves", "size", 100)
3        .accept("application/json")
4        .body();
5System.out.println("Response was: " + response);
6
Full Screen
copy
1int responseCode = httpURLConnection.getResponseCode();
2
3if (responseCode == HttpURLConnection.HTTP_OK) {
4
Full Screen
copy
1String url = "http://example.com";
2String charset = "UTF-8";  // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()
3String param1 = "value1";
4String param2 = "value2";
5// ...
6
7String query = String.format("param1=%s&param2=%s",
8    URLEncoder.encode(param1, charset),
9    URLEncoder.encode(param2, charset));
10
Full Screen
copy
1URLConnection connection = new URL(url + "?" + query).openConnection();
2connection.setRequestProperty("Accept-Charset", charset);
3InputStream response = connection.getInputStream();
4// ...
5
Full Screen
copy
1InputStream response = new URL(url).openStream();
2// ...
3
Full Screen
copy
1try (Scanner scanner = new Scanner(response)) {
2    String responseBody = scanner.useDelimiter("\\A").next();
3    System.out.println(responseBody);
4}
5
Full Screen
copy
1URLConnection connection = new URL(url).openConnection();
2connection.setDoOutput(true); // Triggers POST.
3connection.setRequestProperty("Accept-Charset", charset);
4connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
5
6try (OutputStream output = connection.getOutputStream()) {
7    output.write(query.getBytes(charset));
8}
9
10InputStream response = connection.getInputStream();
11// ...
12
Full Screen
copy
1HttpURLConnection httpConnection = (HttpURLConnection) new URL(url).openConnection();
2httpConnection.setRequestMethod("POST");
3// ...
4
Full Screen
copy
1    int status = httpConnection.getResponseCode();
2
Full Screen
copy
1    String contentType = connection.getHeaderField("Content-Type");
2    String charset = null;
3
4    for (String param : contentType.replace(" ", "").split(";")) {
5        if (param.startsWith("charset=")) {
6            charset = param.split("=", 2)[1];
7            break;
8        }
9    }
10
11    if (charset != null) {
12        try (BufferedReader reader = new BufferedReader(new InputStreamReader(response, charset))) {
13            for (String line; (line = reader.readLine()) != null;) {
14                // ... System.out.println(line)?
15            }
16        }
17    } else {
18        // It's likely binary content, use InputStream/OutputStream.
19    }
20
Full Screen
copy
1// First set the default cookie manager.
2CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
3
4// All the following subsequent URLConnections will use the same cookie manager.
5URLConnection connection = new URL(url).openConnection();
6// ...
7
8connection = new URL(url).openConnection();
9// ...
10
11connection = new URL(url).openConnection();
12// ...
13
Full Screen
copy
1// Gather all cookies on the first request.
2URLConnection connection = new URL(url).openConnection();
3List<String> cookies = connection.getHeaderFields().get("Set-Cookie");
4// ...
5
6// Then use the same cookies on all subsequent requests.
7connection = new URL(url).openConnection();
8for (String cookie : cookies) {
9    connection.addRequestProperty("Cookie", cookie.split(";", 2)[0]);
10}
11// ...
12
Full Screen
copy
1httpConnection.setFixedLengthStreamingMode(contentLength);
2
Full Screen
copy
1httpConnection.setChunkedStreamingMode(1024);
2
Full Screen
copy
1connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"); // Do as if you're using Chrome 41 on Windows 7.
2
Full Screen
copy
1InputStream error = ((HttpURLConnection) connection).getErrorStream();
2
Full Screen
copy
1System.setProperty("http.keepAlive", "false");
2
Full Screen
copy
1String param = "value";
2File textFile = new File("/path/to/file.txt");
3File binaryFile = new File("/path/to/file.bin");
4String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
5String CRLF = "\r\n"; // Line separator required by multipart/form-data.
6URLConnection connection = new URL(url).openConnection();
7connection.setDoOutput(true);
8connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
9
10try (
11    OutputStream output = connection.getOutputStream();
12    PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
13) {
14    // Send normal param.
15    writer.append("--" + boundary).append(CRLF);
16    writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
17    writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
18    writer.append(CRLF).append(param).append(CRLF).flush();
19
20    // Send text file.
21    writer.append("--" + boundary).append(CRLF);
22    writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + textFile.getName() + "\"").append(CRLF);
23    writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset!
24    writer.append(CRLF).flush();
25    Files.copy(textFile.toPath(), output);
26    output.flush(); // Important before continuing with writer!
27    writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
28
29    // Send binary file.
30    writer.append("--" + boundary).append(CRLF);
31    writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF);
32    writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);
33    writer.append("Content-Transfer-Encoding: binary").append(CRLF);
34    writer.append(CRLF).flush();
35    Files.copy(binaryFile.toPath(), output);
36    output.flush(); // Important before continuing with writer!
37    writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
38
39    // End of multipart/form-data.
40    writer.append("--" + boundary + "--").append(CRLF).flush();
41}
42
Full Screen
copy
1static {
2    TrustManager[] trustAllCertificates = new TrustManager[] {
3        new X509TrustManager() {
4            @Override
5            public X509Certificate[] getAcceptedIssuers() {
6                return null; // Not relevant.
7            }
8            @Override
9            public void checkClientTrusted(X509Certificate[] certs, String authType) {
10                // Do nothing. Just allow them all.
11            }
12            @Override
13            public void checkServerTrusted(X509Certificate[] certs, String authType) {
14                // Do nothing. Just allow them all.
15            }
16        }
17    };
18
19    HostnameVerifier trustAllHostnames = new HostnameVerifier() {
20        @Override
21        public boolean verify(String hostname, SSLSession session) {
22            return true; // Just allow them all.
23        }
24    };
25
26    try {
27        System.setProperty("jsse.enableSNIExtension", "false");
28        SSLContext sc = SSLContext.getInstance("SSL");
29        sc.init(null, trustAllCertificates, new SecureRandom());
30        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
31        HttpsURLConnection.setDefaultHostnameVerifier(trustAllHostnames);
32    }
33    catch (GeneralSecurityException e) {
34        throw new ExceptionInInitializerError(e);
35    }
36}
37
Full Screen
copy
1public Synchronized class service(ServletRequest request,ServletResponse response)throws ServletException,IOException
2
Full Screen
copy
1Synchronized(Object)
2
3{
4
5----Instructions-----
6
7}
8
copy
1public class ExampleServlet extends HttpServlet {
2
3    private Object thisIsNOTThreadSafe;
4
5    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
6        Object thisIsThreadSafe;
7
8        thisIsNOTThreadSafe = request.getParameter("foo"); // BAD!! Shared among all requests!
9        thisIsThreadSafe = request.getParameter("foo"); // OK, this is thread safe.
10    } 
11}
12
Full Screen
copy
1public static String getRandomString(int length)
2{
3    String randomStr = UUID.randomUUID().toString();
4    while(randomStr.length() < length) {
5        randomStr += UUID.randomUUID().toString();
6    }
7    return randomStr.substring(0, length);
8}
9
Full Screen
copy
1 public String generateRandomString(int length) {
2    String randomString = "";
3
4    final char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890".toCharArray();
5    final Random random = new Random();
6    for (int i = 0; i < length; i++) {
7        randomString = randomString + chars[random.nextInt(chars.length)];
8    }
9
10    return randomString;
11}
12
Full Screen
copy
1public static String randomSeriesForThreeCharacter() {
2    Random r = new Random();
3    String value = "";
4    char random_Char ;
5    for(int i=0; i<10; i++)
6    {
7        random_Char = (char) (48 + r.nextInt(74));
8        value = value + random_char;
9    }
10    return value;
11}
12
Full Screen
copy
1import org.apache.commons.lang.RandomStringUtils;
2RandomStringUtils.randomAlphanumeric(64);
3
Full Screen
copy
1(for (i <- 0 until rnd.nextInt(64)) yield { 
2  ('0' + rnd.nextInt(64)).asInstanceOf[Char] 
3}) mkString("")
4
Full Screen
copy
1String.valueOf(CharStream.random('0', 'z').filter(c -> N.isLetterOrDigit(c)).limit(12).toArray())
2
Full Screen
copy
1N.uuid() // E.g.: "e812e749-cf4c-4959-8ee1-57829a69a80f". length is 36.
2N.guid() // E.g.: "0678ce04e18945559ba82ddeccaabfcd". length is 32 without '-'
3
Full Screen
copy
1Long.toString(Math.abs( UUID.randomUUID().getLeastSignificantBits(), 36));
2
Full Screen
copy
1private static final String NUMBERS = "0123456789";
2private static final String UPPER_ALPHABETS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
3private static final String LOWER_ALPHABETS = "abcdefghijklmnopqrstuvwxyz";
4private static final String SPECIALCHARACTERS = "@#$%&*";
5private static final int MINLENGTHOFPASSWORD = 8;
6
7public static String getRandomPassword() {
8    StringBuilder password = new StringBuilder();
9    int j = 0;
10    for (int i = 0; i < MINLENGTHOFPASSWORD; i++) {
11        password.append(getRandomPasswordCharacters(j));
12        j++;
13        if (j == 3) {
14            j = 0;
15        }
16    }
17    return password.toString();
18}
19
20private static String getRandomPasswordCharacters(int pos) {
21    Random randomNum = new Random();
22    StringBuilder randomChar = new StringBuilder();
23    switch (pos) {
24        case 0:
25            randomChar.append(NUMBERS.charAt(randomNum.nextInt(NUMBERS.length() - 1)));
26            break;
27        case 1:
28            randomChar.append(UPPER_ALPHABETS.charAt(randomNum.nextInt(UPPER_ALPHABETS.length() - 1)));
29            break;
30        case 2:
31            randomChar.append(SPECIALCHARACTERS.charAt(randomNum.nextInt(SPECIALCHARACTERS.length() - 1)));
32            break;
33        case 3:
34            randomChar.append(LOWER_ALPHABETS.charAt(randomNum.nextInt(LOWER_ALPHABETS.length() - 1)));
35            break;
36    }
37    return randomChar.toString();
38}
39
Full Screen
copy
1import java.util.*;
2import javax.swing.*;
3
4public class alphanumeric {
5    public static void main(String args[]) {
6        String nval, lenval;
7        int n, len;
8
9        nval = JOptionPane.showInputDialog("Enter number of codes you require: ");
10        n = Integer.parseInt(nval);
11
12        lenval = JOptionPane.showInputDialog("Enter code length you require: ");
13        len = Integer.parseInt(lenval);
14
15        find(n, len);
16    }
17
18    public static void find(int n, int length) {
19        String str1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
20        StringBuilder sb = new StringBuilder(length);
21        Random r = new Random();
22
23        System.out.println("\n\t Unique codes are \n\n");
24        for(int i=0; i<n; i++) {
25            for(int j=0; j<length; j++) {
26                sb.append(str1.charAt(r.nextInt(str1.length())));
27            }
28            System.out.println("  " + sb.toString());
29            sb.delete(0, length);
30        }
31    }
32}
33
Full Screen
copy
1import org.apache.commons.lang3.RandomStringUtils;
2
3String keyLength = 20;
4RandomStringUtils.randomAlphanumeric(keylength);
5
Full Screen
copy
1public String randomString(int length, String characterSet) {
2    return IntStream.range(0, length).map(i -> new SecureRandom().nextInt(characterSet.length())).mapToObj(randomInt -> characterSet.substring(randomInt, randomInt + 1)).collect(Collectors.joining());
3}
4
5@Test
6public void buildFiveRandomStrings() {
7    for (int q = 0; q < 5; q++) {
8        System.out.println(randomString(10, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")); // The character set can basically be anything
9    }
10}
11
Full Screen
copy
1public String randomString(int length, String characterSet) {
2    StringBuilder sb = new StringBuilder(); // Consider using StringBuffer if needed
3    for (int i = 0; i < length; i++) {
4        int randomInt = new SecureRandom().nextInt(characterSet.length());
5        sb.append(characterSet.substring(randomInt, randomInt + 1));
6    }
7    return sb.toString();
8}
9
10@Test
11public void buildFiveRandomStrings() {
12    for (int q = 0; q < 5; q++) {
13        System.out.println(randomString(10, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")); // The character set can basically be anything
14    }
15}
16
Full Screen
copy
1UUID.randomUUID().toString().replace("-", "")
2
Full Screen
copy
1import java.util.Date;
2import java.util.Random;
3
4public class RandomGenerator {
5
6  private static Random random = new Random((new Date()).getTime());
7
8    public static String generateRandomString(int length) {
9      char[] values = {'a','b','c','d','e','f','g','h','i','j',
10               'k','l','m','n','o','p','q','r','s','t',
11               'u','v','w','x','y','z','0','1','2','3',
12               '4','5','6','7','8','9'};
13
14      String out = "";
15
16      for (int i=0;i<length;i++) {
17          int idx=random.nextInt(values.length);
18          out += values[idx];
19      }
20      return out;
21    }
22}
23
Full Screen
copy
1public static String getRandomString(int length) {
2    final String characters = "[email protected]#$%^&*()_+";
3    StringBuilder result = new StringBuilder();
4
5    while(length > 0) {
6        Random rand = new Random();
7        result.append(characters.charAt(rand.nextInt(characters.length())));
8        length--;
9    }
10    return result.toString();
11}
12
Full Screen
copy
1/**
2 * Generate a random hex encoded string token of the specified length
3 *  
4 * @param length
5 * @return random hex string
6 */
7public static synchronized String generateUniqueToken(Integer length){ 
8    byte random[] = new byte[length];
9    Random randomGenerator = new Random();
10    StringBuffer buffer = new StringBuffer();
11
12    randomGenerator.nextBytes(random);
13
14    for (int j = 0; j < random.length; j++) {
15        byte b1 = (byte) ((random[j] & 0xf0) >> 4);
16        byte b2 = (byte) (random[j] & 0x0f);
17        if (b1 < 10)
18            buffer.append((char) ('0' + b1));
19        else
20            buffer.append((char) ('A' + (b1 - 10)));
21        if (b2 < 10)
22            buffer.append((char) ('0' + b2));
23        else
24            buffer.append((char) ('A' + (b2 - 10)));
25    }
26    return (buffer.toString());
27}
28
29@Test
30public void testGenerateUniqueToken(){
31    Set set = new HashSet();
32    String token = null;
33    int size = 16;
34
35    /* Seems like we should be able to generate 500K tokens 
36     * without a duplicate 
37     */
38    for (int i=0; i<500000; i++){
39        token = Utility.generateUniqueToken(size);
40
41        if (token.length() != size * 2){
42            fail("Incorrect length");
43        } else if (set.contains(token)) {
44            fail("Duplicate token generated");
45        } else{
46            set.add(token);
47        }
48    }
49}
50
Full Screen
copy
1/*
2 * The random generator used by this class to create random keys.
3 * In a holder class to defer initialization until needed.
4 */
5private static class RandomHolder {
6    static final Random random = new SecureRandom();
7    public static String randomKey(int length) {
8        return String.format("%"+length+"s", new BigInteger(length*5/*base 32,2^5*/, random)
9            .toString(32)).replace('\u0020', '0');
10    }
11}
12
Full Screen
copy
1import java.util.Random;
2
3public class passGen{
4    // Version 1.0
5    private static final String dCase = "abcdefghijklmnopqrstuvwxyz";
6    private static final String uCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
7    private static final String sChar = "[email protected]#$%^&*";
8    private static final String intChar = "0123456789";
9    private static Random r = new Random();
10    private static StringBuilder pass = new StringBuilder();
11
12    public static void main (String[] args) {
13        System.out.println ("Generating pass...");
14        while (pass.length () != 16){
15            int rPick = r.nextInt(4);
16            if (rPick == 0){
17                int spot = r.nextInt(26);
18                pass.append(dCase.charAt(spot));
19            } else if (rPick == 1) {
20                int spot = r.nextInt(26);
21                pass.append(uCase.charAt(spot));
22            } else if (rPick == 2) {
23                int spot = r.nextInt(8);
24                pass.append(sChar.charAt(spot));
25            } else {
26                int spot = r.nextInt(10);
27                pass.append(intChar.charAt(spot));
28            }
29        }
30        System.out.println ("Generated Pass: " + pass.toString());
31    }
32}
33
Full Screen
copy
1public static String generateSessionKey(int length){
2    String alphabet =
3        new String("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"); // 9
4
5    int n = alphabet.length(); // 10
6
7    String result = new String();
8    Random r = new Random(); // 11
9
10    for (int i=0; i<length; i++) // 12
11        result = result + alphabet.charAt(r.nextInt(n)); //13
12
13    return result;
14}
15
Full Screen
copy
1static final Random random = new Random(); // Or SecureRandom
2static final int startChar = (int) '!';
3static final int endChar = (int) '~';
4
5static String randomString(final int maxLength) {
6  final int length = random.nextInt(maxLength + 1);
7  return random.ints(length, startChar, endChar + 1)
8        .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
9        .toString();
10}
11
Full Screen
copy
1import java.util.UUID
2
3UUID.randomUUID().toString();
4
Full Screen
copy
1Random r = new java.util.Random ();
2String s = Long.toString (r.nextLong () & Long.MAX_VALUE, 36);
3
Full Screen
copy
1import static java.lang.Math.round;
2import static java.lang.Math.random;
3import static java.lang.Math.pow;
4import static java.lang.Math.abs;
5import static java.lang.Math.min;
6import static org.apache.commons.lang.StringUtils.leftPad
7
8public class RandomAlphaNum {
9  public static String gen(int length) {
10    StringBuffer sb = new StringBuffer();
11    for (int i = length; i > 0; i -= 12) {
12      int n = min(12, abs(i));
13      sb.append(leftPad(Long.toString(round(random() * pow(36, n)), 36), n, '0'));
14    }
15    return sb.toString();
16  }
17}
18
Full Screen
copy
1scala> RandomAlphaNum.gen(42)
2res3: java.lang.String = uja6snx21bswf9t89s00bxssu8g6qlu16ffzqaxxoy
3
Full Screen
copy
1// "0123456789" + "ABCDE...Z"
2String validCharacters = $('0', '9').join() + $('A', 'Z').join();
3
4String randomString(int length) {
5    return $(validCharacters).shuffle().slice(length).toString();
6}
7
8@Test
9public void buildFiveRandomStrings() {
10    for (int i : $(5)) {
11        System.out.println(randomString(12));
12    }
13}
14
Full Screen
copy
1DKL1SBH9UJWC
2JH7P0IT21EA5
35DTI72EO6SFU
4HQUMJTEBNF7Y
51HCR6SKYWGT7
6
Full Screen
copy
1SecureRandom rnd = new SecureRandom();
2byte[] token = new byte[byteLength];
3rnd.nextBytes(token);
4
Full Screen
copy
1public static String generateRandomHexToken(int byteLength) {
2    SecureRandom secureRandom = new SecureRandom();
3    byte[] token = new byte[byteLength];
4    secureRandom.nextBytes(token);
5    return new BigInteger(1, token).toString(16); // Hexadecimal encoding
6}
7
8//generateRandomHexToken(16) -> 2189df7475e96aa3982dbeab266497cd
9
Full Screen
copy
1public static String generateRandomBase64Token(int byteLength) {
2    SecureRandom secureRandom = new SecureRandom();
3    byte[] token = new byte[byteLength];
4    secureRandom.nextBytes(token);
5    return Base64.getUrlEncoder().withoutPadding().encodeToString(token); //base64 encoding
6}
7
8//generateRandomBase64Token(16) -> EEcCCAYuUcQk7IuzdaPzrg
9
Full Screen
copy
1IdMask<Long> idMask = IdMasks.forLongIds(Config.builder(key).build());
2String maskedId = idMask.mask(id);
3// Example: NPSBolhMyabUBdTyanrbqT8
4long originalId = idMask.unmask(maskedId);
5
Full Screen
copy
1Long.toHexString(Double.doubleToLongBits(Math.random()));
2
Full Screen
copy
1RandomStringUtils.randomAlphanumeric(20).toUpperCase();
2
Full Screen
copy
1RandomStringGenerator randomStringGenerator =
2        new RandomStringGenerator.Builder()
3                .withinRange('0', 'z')
4                .filteredBy(CharacterPredicates.LETTERS, CharacterPredicates.DIGITS)
5                .build();
6randomStringGenerator.generate(12); // toUpperCase() if you want
7
Full Screen
copy
1static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2static SecureRandom rnd = new SecureRandom();
3
4String randomString(int len){
5   StringBuilder sb = new StringBuilder(len);
6   for(int i = 0; i < len; i++)
7      sb.append(AB.charAt(rnd.nextInt(AB.length())));
8   return sb.toString();
9}
10
Full Screen
copy
1import java.util.UUID;
2
3public class randomStringGenerator {
4    public static void main(String[] args) {
5        System.out.println(generateString());
6    }
7
8    public static String generateString() {
9        String uuid = UUID.randomUUID().toString();
10        return "uuid = " + uuid;
11    }
12}
13
Full Screen
copy
1uuid = 2d7428a6-b58c-4008-8575-f05549f16316
2
Full Screen
copy
1public class RandomString {
2
3    /**
4     * Generate a random string.
5     */
6    public String nextString() {
7        for (int idx = 0; idx < buf.length; ++idx)
8            buf[idx] = symbols[random.nextInt(symbols.length)];
9        return new String(buf);
10    }
11
12    public static final String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
13
14    public static final String lower = upper.toLowerCase(Locale.ROOT);
15
16    public static final String digits = "0123456789";
17
18    public static final String alphanum = upper + lower + digits;
19
20    private final Random random;
21
22    private final char[] symbols;
23
24    private final char[] buf;
25
26    public RandomString(int length, Random random, String symbols) {
27        if (length < 1) throw new IllegalArgumentException();
28        if (symbols.length() < 2) throw new IllegalArgumentException();
29        this.random = Objects.requireNonNull(random);
30        this.symbols = symbols.toCharArray();
31        this.buf = new char[length];
32    }
33
34    /**
35     * Create an alphanumeric string generator.
36     */
37    public RandomString(int length, Random random) {
38        this(length, random, alphanum);
39    }
40
41    /**
42     * Create an alphanumeric strings from a secure generator.
43     */
44    public RandomString(int length) {
45        this(length, new SecureRandom());
46    }
47
48    /**
49     * Create session identifiers.
50     */
51    public RandomString() {
52        this(21);
53    }
54
55}
56
Full Screen
copy
1RandomString gen = new RandomString(8, ThreadLocalRandom.current());
2
Full Screen
copy
1RandomString session = new RandomString();
2
Full Screen
copy
1String easy = RandomString.digits + "ACEFGHJKLMNPQRUVWXYabcdefhijkprstuvwx";
2RandomString tickets = new RandomString(23, new SecureRandom(), easy);
3
Full Screen
copy
1var uri = URI.create("https://httpbin.org/get?age=26&isHappy=true");
2var client = HttpClient.newHttpClient();
3var request = HttpRequest
4        .newBuilder()
5        .uri(uri)
6        .header("accept", "application/json")
7        .GET()
8        .build();
9var response = client.send(request, HttpResponse.BodyHandlers.ofString());
10System.out.println(response.statusCode());
11System.out.println(response.body());
12
Full Screen
copy
1var responseAsync = client
2        .sendAsync(request, HttpResponse.BodyHandlers.ofString())
3        .thenApply(HttpResponse::body)
4        .thenAccept(System.out::println);
5// responseAsync.join(); // Wait for completion
6
Full Screen
copy
1var request = HttpRequest
2        .newBuilder()
3        .uri(uri)
4        .version(HttpClient.Version.HTTP_2)
5        .timeout(Duration.ofMinutes(1))
6        .header("Content-Type", "application/json")
7        .header("Authorization", "Bearer fake")
8        .POST(BodyPublishers.ofString("{ title: 'This is cool' }"))
9        .build();
10var response = client.send(request, HttpResponse.BodyHandlers.ofString());
11
Full Screen
copy
1String html = new JdkRequest("http://www.google.com").fetch().body();
2
Full Screen
copy
1OkHttpClient client = new OkHttpClient();
2
Full Screen
copy
1Request request = new Request.Builder()
2      .url(url)
3      .build();
4
Full Screen
copy
1Response response = client.newCall(request).execute();
2
Full Screen
copy
1package org.boon.utils;
2
3import java.io.IOException;
4import java.io.InputStream;
5import java.net.HttpURLConnection;
6import java.net.URL;
7import java.net.URLConnection;
8import java.util.Map;
9
10import static org.boon.utils.IO.read;
11
12public class HTTP {
13
Full Screen
copy
1public static String get(
2        final String url) {
3
4    Exceptions.tryIt(() -> {
5        URLConnection connection;
6        connection = doGet(url, null, null, null);
7        return extractResponseString(connection);
8    });
9    return null;
10}
11
12public static String getWithHeaders(
13        final String url,
14        final Map<String, ? extends Object> headers) {
15    URLConnection connection;
16    try {
17        connection = doGet(url, headers, null, null);
18        return extractResponseString(connection);
19    } catch (Exception ex) {
20        Exceptions.handle(ex);
21        return null;
22    }
23}
24
25public static String getWithContentType(
26        final String url,
27        final Map<String, ? extends Object> headers,
28        String contentType) {
29    URLConnection connection;
30    try {
31        connection = doGet(url, headers, contentType, null);
32        return extractResponseString(connection);
33    } catch (Exception ex) {
34        Exceptions.handle(ex);
35        return null;
36    }
37}
38public static String getWithCharSet(
39        final String url,
40        final Map<String, ? extends Object> headers,
41        String contentType,
42        String charSet) {
43    URLConnection connection;
44    try {
45        connection = doGet(url, headers, contentType, charSet);
46        return extractResponseString(connection);
47    } catch (Exception ex) {
48        Exceptions.handle(ex);
49        return null;
50    }
51}
52
Full Screen
copy
1public static String postBody(
2        final String url,
3        final String body) {
4    URLConnection connection;
5    try {
6        connection = doPost(url, null, "text/plain", null, body);
7        return extractResponseString(connection);
8    } catch (Exception ex) {
9        Exceptions.handle(ex);
10        return null;
11    }
12}
13
14public static String postBodyWithHeaders(
15        final String url,
16        final Map<String, ? extends Object> headers,
17        final String body) {
18    URLConnection connection;
19    try {
20        connection = doPost(url, headers, "text/plain", null, body);
21        return extractResponseString(connection);
22    } catch (Exception ex) {
23        Exceptions.handle(ex);
24        return null;
25    }
26}
27
28
29public static String postBodyWithContentType(
30        final String url,
31        final Map<String, ? extends Object> headers,
32        final String contentType,
33        final String body) {
34
35    URLConnection connection;
36    try {
37        connection = doPost(url, headers, contentType, null, body);
38
39        return extractResponseString(connection);
40
41    } catch (Exception ex) {
42        Exceptions.handle(ex);
43        return null;
44    }
45
46}
47
48
49public static String postBodyWithCharset(
50        final String url,
51        final Map<String, ? extends Object> headers,
52        final String contentType,
53        final String charSet,
54        final String body) {
55
56    URLConnection connection;
57    try {
58        connection = doPost(url, headers, contentType, charSet, body);
59
60        return extractResponseString(connection);
61
62    } catch (Exception ex) {
63        Exceptions.handle(ex);
64        return null;
65    }
66}
67
68private static URLConnection doPost(String url, Map<String, ? extends Object> headers,
69                                    String contentType, String charset, String body
70                                    ) throws IOException {
71    URLConnection connection;/* Handle output. */
72    connection = new URL(url).openConnection();
73    connection.setDoOutput(true);
74    manageContentTypeHeaders(contentType, charset, connection);
75
76    manageHeaders(headers, connection);
77
78    IO.write(connection.getOutputStream(), body, IO.CHARSET);
79    return connection;
80}
81
82private static void manageHeaders(Map<String, ? extends Object> headers, URLConnection connection) {
83    if (headers != null) {
84        for (Map.Entry<String, ? extends Object> entry : headers.entrySet()) {
85            connection.setRequestProperty(entry.getKey(), entry.getValue().toString());
86        }
87    }
88}
89
90private static void manageContentTypeHeaders(String contentType, String charset, URLConnection connection) {
91    connection.setRequestProperty("Accept-Charset", charset == null ? IO.CHARSET : charset);
92    if (contentType!=null && !contentType.isEmpty()) {
93        connection.setRequestProperty("Content-Type", contentType);
94    }
95}
96
97private static URLConnection doGet(String url, Map<String, ? extends Object> headers,
98                                    String contentType, String charset) throws IOException {
99    URLConnection connection;/* Handle output. */
100    connection = new URL(url).openConnection();
101    manageContentTypeHeaders(contentType, charset, connection);
102
103    manageHeaders(headers, connection);
104
105    return connection;
106}
107
108private static String extractResponseString(URLConnection connection) throws IOException {
109/* Handle input. */
110    HttpURLConnection http = (HttpURLConnection)connection;
111    int status = http.getResponseCode();
112    String charset = getCharset(connection.getHeaderField("Content-Type"));
113
114    if (status==200) {
115        return readResponseBody(http, charset);
116    } else {
117        return readErrorResponseBody(http, status, charset);
118    }
119}
120
121private static String readErrorResponseBody(HttpURLConnection http, int status, String charset) {
122    InputStream errorStream = http.getErrorStream();
123    if ( errorStream!=null ) {
124        String error = charset== null ? read( errorStream ) :
125            read( errorStream, charset );
126        throw new RuntimeException("STATUS CODE =" + status + "\n\n" + error);
127    } else {
128        throw new RuntimeException("STATUS CODE =" + status);
129    }
130}
131
132private static String readResponseBody(HttpURLConnection http, String charset) throws IOException {
133    if (charset != null) {
134        return read(http.getInputStream(), charset);
135    } else {
136        return read(http.getInputStream());
137    }
138}
139
140private static String getCharset(String contentType) {
141    if (contentType==null)  {
142        return null;
143    }
144    String charset = null;
145    for (String param : contentType.replace(" ", "").split(";")) {
146        if (param.startsWith("charset=")) {
147            charset = param.split("=", 2)[1];
148            break;
149        }
150    }
151    charset = charset == null ? IO.CHARSET : charset;
152
153    return charset;
154}
155
Full Screen
copy
1static class MyHandler implements HttpHandler {
2    public void handle(HttpExchange t) throws IOException {
3
4        InputStream requestBody = t.getRequestBody();
5        String body = IO.read(requestBody);
6        Headers requestHeaders = t.getRequestHeaders();
7        body = body + "\n" + copy(requestHeaders).toString();
8        t.sendResponseHeaders(200, body.length());
9        OutputStream os = t.getResponseBody();
10        os.write(body.getBytes());
11        os.close();
12    }
13}
14
15
16@Test
17public void testHappy() throws Exception {
18
19    HttpServer server = HttpServer.create(new InetSocketAddress(9212), 0);
20    server.createContext("/test", new MyHandler());
21    server.setExecutor(null); // creates a default executor
22    server.start();
23
24    Thread.sleep(10);
25
26    Map<String,String> headers = map("foo", "bar", "fun", "sun");
27
28    String response = HTTP.postBodyWithContentType("http://localhost:9212/test", headers, "text/plain", "hi mom");
29
30    System.out.println(response);
31
32    assertTrue(response.contains("hi mom"));
33    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));
34
35    response = HTTP.postBodyWithCharset("http://localhost:9212/test", headers, "text/plain", "UTF-8", "hi mom");
36
37    System.out.println(response);
38
39    assertTrue(response.contains("hi mom"));
40    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));
41
42    response = HTTP.postBodyWithHeaders("http://localhost:9212/test", headers, "hi mom");
43
44    System.out.println(response);
45
46    assertTrue(response.contains("hi mom"));
47    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));
48
49    response = HTTP.get("http://localhost:9212/test");
50
51    System.out.println(response);
52
53    response = HTTP.getWithHeaders("http://localhost:9212/test", headers);
54
55    System.out.println(response);
56
57    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));
58
59    response = HTTP.getWithContentType("http://localhost:9212/test", headers, "text/plain");
60
61    System.out.println(response);
62
63    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));
64
65    response = HTTP.getWithCharSet("http://localhost:9212/test", headers, "text/plain", "UTF-8");
66
67    System.out.println(response);
68
69    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));
70
71    Thread.sleep(10);
72
73    server.stop(0);
74}
75
76@Test
77public void testPostBody() throws Exception {
78
79    HttpServer server = HttpServer.create(new InetSocketAddress(9220), 0);
80    server.createContext("/test", new MyHandler());
81    server.setExecutor(null); // creates a default executor
82    server.start();
83
84    Thread.sleep(10);
85
86    Map<String,String> headers = map("foo", "bar", "fun", "sun");
87
88    String response = HTTP.postBody("http://localhost:9220/test", "hi mom");
89
90    assertTrue(response.contains("hi mom"));
91
92    Thread.sleep(10);
93
94    server.stop(0);
95}
96
97@Test(expected = RuntimeException.class)
98public void testSad() throws Exception {
99
100    HttpServer server = HttpServer.create(new InetSocketAddress(9213), 0);
101    server.createContext("/test", new MyHandler());
102    server.setExecutor(null); // creates a default executor
103    server.start();
104
105    Thread.sleep(10);
106
107    Map<String,String> headers = map("foo", "bar", "fun", "sun");
108
109    String response = HTTP.postBodyWithContentType("http://localhost:9213/foo", headers, "text/plain", "hi mom");
110
111    System.out.println(response);
112
113    assertTrue(response.contains("hi mom"));
114    assertTrue(response.contains("Fun=[sun], Foo=[bar]"));
115
116    Thread.sleep(10);
117
118    server.stop(0);
119}
120
Full Screen