Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.net.HttpURLConnection;
- import java.net.URL;
- class Response {
- public int code;
- public String response;
- public Response(int code, String response) {
- this.code = code;
- this.response = response;
- }
- }
- class HttpThing {
- public static Boolean ping(String url) throws IOException {
- HttpURLConnection huc = (HttpURLConnection) (new URL(url)).openConnection();
- int code = huc.getResponseCode();
- return code != HttpURLConnection.HTTP_NOT_FOUND && code != HttpURLConnection.HTTP_FORBIDDEN && code != HttpURLConnection.HTTP_GATEWAY_TIMEOUT;
- }
- public static Response get(String url) throws IOException {
- HttpURLConnection connection = (HttpURLConnection) (new URL(url)).openConnection();
- InputStream responseStream = connection.getInputStream();
- BufferedReader bufferReader = new BufferedReader(new InputStreamReader(responseStream));
- StringBuilder stringBuilder = new StringBuilder();
- String line;
- while ((line = bufferReader.readLine()) != null)
- stringBuilder.append(line);
- responseStream.close();
- bufferReader.close();
- return new Response(connection.getResponseCode(), stringBuilder.toString());
- }
- public static Response post(String url, String data) throws IOException {
- HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
- connection.setRequestMethod("POST");
- connection.setDoOutput(true);
- connection.connect();
- OutputStream output = connection.getOutputStream();
- outputStreamWriter(output, data);
- output.close();
- StringBuilder sb = new StringBuilder();
- BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
- String line;
- while ((line = bufferedReader.readLine()) != null)
- sb.append(line);
- bufferedReader.close();
- return new Response(connection.getResponseCode(), sb.toString());
- }
- public static void outputStreamWriter(OutputStream stream, String data) {
- try {
- byte[] dataBytes = data.getBytes();
- stream.write(dataBytes);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment