import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
public class API {
public static void main(String[] args) throws IOException {
String message = "Hello, how are you?";
String email = "EMAIL";
String apiKey = "API_KEY";
String token = authenticate(email + ":" + apiKey);
System.out.println("provided token:" + token);
System.out.println("please type exit to terminate chat");
System.out.println("chatbot:" + chat(token, message));
}
public static String authenticate(String usrCredit) {
String userAuth = usrCredit;
String basicAuthPayload = "Basic " + Base64.getEncoder().encodeToString(userAuth.getBytes());
BufferedReader httpResponseReader = null;
String result = "";
try {
// Connect to the web server endpoint
URL serverUrl = new URL("http://api.altchat.app/login");
HttpURLConnection urlConnection = (HttpURLConnection) serverUrl.openConnection();
// Set HTTP method as GET
urlConnection.setRequestMethod("GET");
// Include the HTTP Basic Authentication payload
urlConnection.addRequestProperty("Authorization", basicAuthPayload);
// Read response from web server, which will trigger HTTP Basic Authentication
// request to be sent.
httpResponseReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String lineRead;
while ((lineRead = httpResponseReader.readLine()) != null) {
result = result + lineRead;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (httpResponseReader != null) {
try {
httpResponseReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
result = result.split(":")[1];
result = result.replaceAll("}", "");
result = result.replaceAll("\"", "");
return result;
}
public static String chat(String token, String sent) throws IOException {
URL url = new URL("http://api.altchat.app/" + token);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
String result = "";
String jsonInputString = "{\"message\": \"" + sent + "\"}";
try (OutputStream os = con.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
}
try (BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
result = response.toString();
}
return result;
}
}