70 lines
2.6 KiB
Java
70 lines
2.6 KiB
Java
import java.io.BufferedReader;
|
|
import java.io.DataOutputStream;
|
|
import java.io.IOException;
|
|
import java.io.InputStreamReader;
|
|
import java.net.HttpURLConnection;
|
|
import java.net.MalformedURLException;
|
|
import java.net.SocketTimeoutException;
|
|
import java.net.URL;
|
|
import java.net.URLEncoder;
|
|
|
|
public class App {
|
|
|
|
public static void main(String[] args) throws IOException {
|
|
URL url = new URL("http://127.0.0.1:8080/fetch.php");
|
|
HttpURLConnection client = null;
|
|
try {
|
|
client = (HttpURLConnection) url.openConnection();
|
|
|
|
// Additional headers
|
|
client.setRequestProperty("Connection", "close");
|
|
client.setUseCaches(false);
|
|
|
|
// Set the request method to POST
|
|
client.setRequestMethod("POST");
|
|
client.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
|
|
client.setDoOutput(true);
|
|
|
|
// Send the parameters in the request body
|
|
String urlParameters = "username=" + URLEncoder.encode("zlevorantonin", "UTF-8") +
|
|
"&password=" + URLEncoder.encode("Skolajenej!22", "UTF-8");
|
|
|
|
DataOutputStream wr = new DataOutputStream(client.getOutputStream());
|
|
wr.writeBytes(urlParameters);
|
|
wr.flush();
|
|
wr.close();
|
|
|
|
// Get the response code
|
|
int responseCode = client.getResponseCode();
|
|
//System.out.println("Response Code: " + responseCode);
|
|
|
|
// Read the response body
|
|
try (BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()))) {
|
|
String inputLine;
|
|
StringBuilder response = new StringBuilder();
|
|
|
|
while ((inputLine = in.readLine()) != null) {
|
|
response.append(inputLine);
|
|
}
|
|
|
|
// Print the response body
|
|
System.out.println(response.toString());
|
|
}
|
|
|
|
} catch (MalformedURLException error) {
|
|
// Handles an incorrectly entered URL
|
|
System.out.println("malformed URL");
|
|
} catch (SocketTimeoutException error) {
|
|
// Handles URL access timeout.
|
|
System.out.println("socket timeout");
|
|
} catch (IOException error) {
|
|
// Handles input and output errors
|
|
System.out.println("IO exception: " + error.getMessage());
|
|
error.printStackTrace();
|
|
} finally {
|
|
if (client != null) // Make sure the connection is not null.
|
|
client.disconnect();
|
|
}
|
|
}
|
|
}
|