Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.nio.charset.StandardCharsets;
- import java.util.Base64;
- public class RestApiGet {
- private StringBuffer response = new StringBuffer();
- private String output;
- String getOutput()
- {
- return this.output;
- }
- void setOutput(String username, String password, String apiCall) {
- String login = username + ":" + password;
- final byte[] authBytes = login.getBytes(StandardCharsets.UTF_8);
- String encoded = Base64.getEncoder().withoutPadding().encodeToString(authBytes);
- try {
- URL url = new URL("http://192.168.0.25:8080"+apiCall);
- HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- connection.setRequestMethod("GET");
- connection.setRequestProperty("Authorization", "Basic " + encoded);
- connection.setDoOutput(true);
- if (connection.getResponseCode() == 200 ) {
- BufferedReader out = new BufferedReader(
- new InputStreamReader(connection.getInputStream()));
- String inpuLine;
- while ((inpuLine = out.readLine()) != null) {
- this.response.append(inpuLine);
- }
- out.close();
- this.output = this.response.toString();
- }
- else
- System.out.println(connection.getResponseCode());
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- boolean restLogin(String username, String password, String apiCall) {
- String login = username + ":" + password;
- final byte[] authBytes = login.getBytes(StandardCharsets.UTF_8);
- String encoded = Base64.getEncoder().withoutPadding().encodeToString(authBytes);
- try {
- URL url = new URL("http://192.168.0.25:8080"+apiCall);
- HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- connection.setRequestMethod("GET");
- connection.setRequestProperty("Authorization", "Basic " + encoded);
- connection.setDoOutput(true);
- if (connection.getResponseCode() == 200 ) {
- System.out.println("Witaj " + username);
- }
- else{
- System.out.println("Logowanie nieudane, kod błędu:" + connection.getResponseCode());
- return false;
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement