Untitled

mail@pastecode.io avatar
unknown
java
a year ago
2.4 kB
1
Indexable
Never
package ru.yandex.programmers_day;


import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class ProgrammersDayApplication {

	private static final char[] CHARACTERS = "0123456789ABCDEFabcdef".toCharArray();

	public static HttpClient client = HttpClient.newHttpClient();

	public static void main(String[] args) throws IOException, InterruptedException {
		guessString();
	}

	public static void guessString() throws IOException, InterruptedException {
		int length = 8;
		char[] guess = new char[length];

		int low = 0;
		int high = CHARACTERS.length - 1;

		while (low <= high) {
			int mid = low + (high - low) / 2;

			guess[0] = CHARACTERS[mid];

			//тут делаем запрос и узнаем знак
			int x = getMoreOrLess(String.valueOf(guess));
			if (x < 0) {
				high = mid - 1;
			} else if (x > 0) {
				low = mid + 1;
			} else {
				return;
			}
		}
	}



	public static int getMoreOrLess(String guess) throws IOException, InterruptedException {

		System.out.println(guess);

		String json = "{\"password\": \"" + guess + "\"}";

		HttpRequest.BodyPublisher body = HttpRequest.BodyPublishers.ofString(json);
		HttpRequest request = HttpRequest.newBuilder()
				.POST(body)
				.uri(URI.create("http://ya.praktikum.fvds.ru:8080/dev-day/task/3"))
				.header("AUTH_TOKEN", "e4dfc14a-9afb-4867-94d2-29351cc15431")
				.header("content-type", "application/json")
				.build();

		HttpResponse.BodyHandler<String> handler = HttpResponse.BodyHandlers.ofString();
		HttpResponse<String> response = client.send(request, handler);

		JsonElement jsonElement = JsonParser.parseString(json);
		JsonObject jsonObject = jsonElement.getAsJsonObject();
		String prompt;
		try {
			prompt = jsonObject.get("prompt").getAsString();
			if (prompt.equals("<pass")) {
				return -1;
			} else if (prompt.equals(">pass")) {
				return 1;
			} else {
				System.out.println("Подбор завершен. " + guess);
				System.out.println("Код ответа: " + response.statusCode());
				System.out.println("Тело ответа: " + response.body());
				return 0;
			}
		} catch (Exception e) {
			System.out.println(guess);
		}

		return 0;
	}
}