Нужно написать java код для нажатия на Restapi.
Я использую API get для авторизации. После авторизации я должен нажать на метод сообщения. Я получаю ответ на запрос как 200, но ответ метода 401 не авторизован.
public static void main(String[] args) throws IOException {
getRequest();
postRequest();
}
public static void getRequest() throws IOException {
URL urlForGetRequest = new URL("https://****/ws/auth/login?usr_id=***&password=***");
HttpURLConnection connection = (HttpURLConnection) urlForGetRequest.openConnection();
connection.setRequestMethod("GET");
// String cookiesHeader = connection.getHeaderField("Set-Cookie");
// connection.setRequestProperty("Authorization", apiKeyVal);
// System.out.println(session);
// HttpSession session = connection.getSession();
int responseCode = connection.getResponseCode();
System.out.println(responseCode);
}
public static void postRequest() throws IOException {
final String inboundshipment = InboundShipmentJsonCreator.json();
URL obj = new URL("https://****/ws/integration/api/**");
HttpURLConnection postConnection = (HttpURLConnection) obj.openConnection();
postConnection.setRequestMethod("POST");
postConnection.setRequestProperty("Content-Type", "application/json");
postConnection.setRequestProperty("Accept", "application/json");
postConnection.setDoOutput(true);
// postConnection.setRequestProperty("Set-Cookie", cookiesHeader);
OutputStream os = postConnection.getOutputStream();
os.write(inboundshipment.getBytes());
os.flush();
os.close();
int responseCode = postConnection.getResponseCode();
System.out.println("POST Response Code : " + responseCode);
System.out.println("POST Response Message : " + postConnection.getResponseMessage());
if (responseCode == HttpURLConnection.HTTP_CREATED) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
postConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in .readLine()) != null) {
response.append(inputLine);
} in .close();
// print result
System.out.println(response.toString());
} else {
System.out.println("POST NOT WORKED");
}
}
}