Skip to content

Instantly share code, notes, and snippets.

@mikberg
Created March 6, 2018 09:54
Show Gist options
  • Save mikberg/4c5b9b6a5a2ac1f0a29e2589f610fa0f to your computer and use it in GitHub Desktop.
Save mikberg/4c5b9b6a5a2ac1f0a29e2589f610fa0f to your computer and use it in GitHub Desktop.
Deadly Dungeon Java Snippet
/*
* Copyright (c) 2017, Just AS. All rights reserved.
*/
package com.gojust.deadlydungeon.client;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Client {
private static String url = "http://deadly-dungeon.gojust.eu";
public static class InvalidDirectionException extends Exception {
private static final long serialVersionUID = -2071306614069491368L;
public InvalidDirectionException(final String message) {
super(message);
}
}
public static void main(final String[] args) {
try {
System.out.println(Client.getMap());
System.out.println("---");
System.out.println(Client.walk('S'));
} catch (final Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String getMap() throws IOException {
final URL url = new URL(Client.url);
final HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "text/plain");
try {
return Client.getMapFromConnection(con);
} finally {
con.disconnect();
}
}
public static String walk(final char direction) throws IOException, InvalidDirectionException {
final URL url = new URL(Client.url);
final HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "text/plain");
con.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.write(direction);
}
try {
if (con.getResponseCode() == 400) {
throw new InvalidDirectionException("Invalid direction");
}
return Client.getMapFromConnection(con);
} finally {
con.disconnect();
}
}
private static String getMapFromConnection(final HttpURLConnection con) throws IOException {
final BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
final StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine + "\n");
}
in.close();
return content.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment