Added Auth-Header

This commit is contained in:
Marc Beyer 2022-01-11 17:12:37 +01:00
parent 12fce27d04
commit ea6420e234
2 changed files with 25 additions and 5 deletions

View File

@ -34,7 +34,8 @@ public class DataController {
USER_ID = Long.parseLong(httpRequest.sendPostRequest(
LOGIN_ENDPOINT,
"login=" + username
+ "&password=" + password
+ "&password=" + password,
false
));
} catch (Exception e) {
e.printStackTrace();
@ -45,7 +46,7 @@ public class DataController {
public void createEvent(Event event) {
try {
System.out.println(httpRequest.sendPostRequest(ADD_EVENT_ENDPOINT, event.getAsUrlParam()));
System.out.println(httpRequest.sendPostRequest(ADD_EVENT_ENDPOINT, event.getAsUrlParam(), true));
} catch (Exception e) {
throw new RuntimeException("Es konnte keine Verbindung mit dem Server hergestellt werden.");
}
@ -53,7 +54,7 @@ public class DataController {
public void deleteEvent(int eventId) {
try {
System.out.println(httpRequest.sendPostRequest(DELETE_EVENT_ENDPOINT, "eventId=" + eventId));
System.out.println(httpRequest.sendPostRequest(DELETE_EVENT_ENDPOINT, "eventId=" + eventId, true));
} catch (Exception e) {
e.printStackTrace();
}
@ -63,7 +64,7 @@ public class DataController {
ArrayList<Event> eventList = new ArrayList<>();
try {
String jsonResponse = httpRequest.sendPostRequest(ALL_EVENTS_ENDPOINT, "userId=" + USER_ID);
String jsonResponse = httpRequest.sendPostRequest(ALL_EVENTS_ENDPOINT, "userId=" + USER_ID, true);
System.out.println(jsonResponse);
ObjectMapper objectMapper = new ObjectMapper();

View File

@ -9,10 +9,23 @@ import java.nio.charset.StandardCharsets;
import java.util.Arrays;
public class HttpRequest {
public String sendPostRequest(String urlString, String urlParameters) throws Exception {
public String sendPostRequest(String urlString, String urlParameters, boolean sendAuth) throws Exception {
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
/*
URL url = new URL("http://test.de:8080/event/add");
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("POST");
http.setDoOutput(true);
http.setRequestProperty("Accept", "application/json");
http.setRequestProperty("Authorization", "Bearer {token}");
http.setRequestProperty("Content-Type", "");
http.setRequestProperty("Content-Length", "0");
System.out.println(http.getResponseCode() + " " + http.getResponseMessage());
http.disconnect();
*/
URL url = new URL(urlString);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
@ -23,6 +36,12 @@ public class HttpRequest {
con.setRequestProperty("charset", "utf-8");
con.setRequestProperty("Content-Length", Integer.toString(postDataLength));
con.setUseCaches(false);
if(sendAuth){
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Authorization", "Bearer {token}");
}
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.write(postData);
}