]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/utils/NetworkUtil.java
c9f0151ba4b84b12175bbf828eb425e7607c07f8
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / utils / NetworkUtil.java
1 /*
2  * Copyright © 2020 Damyan Ivanov.
3  * This file is part of MoLe.
4  * MoLe is free software: you can distribute it and/or modify it
5  * under the term of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your opinion), any later version.
8  *
9  * MoLe is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License terms for details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with MoLe. If not, see <https://www.gnu.org/licenses/>.
16  */
17
18 package net.ktnx.mobileledger.utils;
19
20 import androidx.annotation.NonNull;
21
22 import net.ktnx.mobileledger.model.MobileLedgerProfile;
23
24 import org.jetbrains.annotations.NotNull;
25
26 import java.io.IOException;
27 import java.net.HttpURLConnection;
28 import java.net.URL;
29
30 import static net.ktnx.mobileledger.utils.Logger.debug;
31
32 public final class NetworkUtil {
33     private static final int thirtySeconds = 30000;
34     @NotNull
35     public static HttpURLConnection prepareConnection(@NonNull MobileLedgerProfile profile,
36                                                       @NonNull String path) throws IOException {
37         return prepareConnection(profile.getUrl(), path, profile.isAuthEnabled());
38     }
39     public static HttpURLConnection prepareConnection(@NonNull String url, @NonNull String path,
40                                                       boolean authEnabled) throws IOException {
41         String connectURL = url;
42         if (!connectURL.endsWith("/"))
43             connectURL += "/";
44         connectURL += path;
45         debug("network", "Connecting to " + connectURL);
46         HttpURLConnection http = (HttpURLConnection) new URL(connectURL).openConnection();
47         http.setAllowUserInteraction(true);
48         http.setRequestProperty("Accept-Charset", "UTF-8");
49         http.setInstanceFollowRedirects(false);
50         http.setUseCaches(false);
51         http.setReadTimeout(thirtySeconds);
52         http.setConnectTimeout(thirtySeconds);
53
54         return http;
55     }
56 }