summaryrefslogtreecommitdiff
path: root/src/main/java/com/mavlushechka/a1qa/utils/URLConnectionManager.java
blob: 286df12476c9ba00fb4232af0a6cf56d423deea0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.mavlushechka.a1qa.utils;

import com.mavlushechka.a1qa.driverUtils.HttpURLConnectionFactory;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;

public class URLConnectionManager {

    public static String get(String spec) throws IOException {
        StringBuilder stringBuilder = new StringBuilder();

        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(HttpURLConnectionFactory.createHttpURLConnection(spec, "GET", false).getInputStream()))) {
            String inputLine;

            while ((inputLine = bufferedReader.readLine()) != null) {
                stringBuilder.append(inputLine);
            }
        }
        return stringBuilder.toString();
    }

    public static String post(String spec, String content) throws IOException {
        HttpURLConnection httpURLConnection = HttpURLConnectionFactory.createHttpURLConnection(spec, "POST", true);
        StringBuilder stringBuilder = new StringBuilder();

        try (DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream())) {
            dataOutputStream.writeBytes(content);
            dataOutputStream.flush();
        }
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()))) {
            String inputLine;

            while ((inputLine = bufferedReader.readLine()) != null) {
                stringBuilder.append(inputLine);
            }
        }
        return stringBuilder.toString();
    }

    public static int getResponseCode(String spec, String requestMethod) throws IOException {
        return HttpURLConnectionFactory.createHttpURLConnection(spec, requestMethod, false).getResponseCode();
    }

}