Browse Source

implement simple http api to make get requests

feature-password-validator-pwned-password-check
binsky 3 years ago
parent
commit
16d309e1e5
  1. 27
      src/main/java/HttpApi.java
  2. 19
      src/test/java/HttpApiTest.java

27
src/main/java/HttpApi.java

@ -0,0 +1,27 @@
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpApi {
public static String sendHttpGETRequest(String url) throws IOException {
URL obj = new URL(url);
HttpURLConnection httpURLConnection = (HttpURLConnection) obj.openConnection();
httpURLConnection.setRequestMethod("GET");
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in .readLine()) != null) {
response.append(inputLine);
} in .close();
return response.toString();
}
return null;
}
}

19
src/test/java/HttpApiTest.java

@ -0,0 +1,19 @@
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.Objects;
import static org.junit.jupiter.api.Assertions.*;
class HttpApiTest {
@Test
void sendHttpGETRequest() {
assertDoesNotThrow(() -> HttpApi.sendHttpGETRequest("https://httpbin.org/get"));
try {
assertTrue(Objects.requireNonNull(HttpApi.sendHttpGETRequest("https://httpbin.org/get")).contains("args"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
Loading…
Cancel
Save