TerrificTable55

Untitled

Oct 8th, 2022
1,564
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.35 KB | None | 0 0
  1. import java.io.*;
  2. import java.net.HttpURLConnection;
  3. import java.net.URL;
  4.  
  5. class Response {
  6.     public int code;
  7.     public String response;
  8.  
  9.     public Response(int code, String response) {
  10.         this.code = code;
  11.         this.response = response;
  12.     }
  13. }
  14.  
  15. class HttpThing {
  16.  
  17.     public static Boolean ping(String url) throws IOException {
  18.         HttpURLConnection huc = (HttpURLConnection) (new URL(url)).openConnection();
  19.         int code = huc.getResponseCode();
  20.         return code != HttpURLConnection.HTTP_NOT_FOUND && code != HttpURLConnection.HTTP_FORBIDDEN && code != HttpURLConnection.HTTP_GATEWAY_TIMEOUT;
  21.     }
  22.  
  23.     public static Response get(String url) throws IOException {
  24.         HttpURLConnection connection = (HttpURLConnection) (new URL(url)).openConnection();
  25.         InputStream responseStream = connection.getInputStream();
  26.         BufferedReader bufferReader = new BufferedReader(new InputStreamReader(responseStream));
  27.         StringBuilder stringBuilder = new StringBuilder();
  28.  
  29.         String line;
  30.         while ((line = bufferReader.readLine()) != null)
  31.             stringBuilder.append(line);
  32.  
  33.         responseStream.close();
  34.         bufferReader.close();
  35.  
  36.         return new Response(connection.getResponseCode(), stringBuilder.toString());
  37.     }
  38.  
  39.     public static Response post(String url, String data) throws IOException {
  40.         HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
  41.         connection.setRequestMethod("POST");
  42.         connection.setDoOutput(true);
  43.         connection.connect();
  44.         OutputStream output = connection.getOutputStream();
  45.         outputStreamWriter(output, data);
  46.         output.close();
  47.         StringBuilder sb = new StringBuilder();
  48.         BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  49.  
  50.         String line;
  51.         while ((line = bufferedReader.readLine()) != null)
  52.             sb.append(line);
  53.         bufferedReader.close();
  54.  
  55.         return new Response(connection.getResponseCode(), sb.toString());
  56.     }
  57.  
  58.  
  59.  
  60.  
  61.     public static void outputStreamWriter(OutputStream stream, String data) {
  62.         try {
  63.             byte[] dataBytes = data.getBytes();
  64.             stream.write(dataBytes);
  65.         } catch (IOException e) {
  66.             e.printStackTrace();
  67.         }
  68.     }
  69.  
  70. }
  71.  
Advertisement
Add Comment
Please, Sign In to add comment