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.
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.
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/>.
18 package net.ktnx.mobileledger.utils;
20 import androidx.annotation.NonNull;
22 import net.ktnx.mobileledger.db.Profile;
24 import org.jetbrains.annotations.NotNull;
26 import java.io.IOException;
27 import java.net.HttpURLConnection;
30 import static net.ktnx.mobileledger.utils.Logger.debug;
32 public final class NetworkUtil {
33 private static final int thirtySeconds = 30000;
35 public static HttpURLConnection prepareConnection(@NonNull Profile profile,
36 @NonNull String path) throws IOException {
37 return prepareConnection(profile.getUrl(), path, profile.useAuthentication());
39 public static HttpURLConnection prepareConnection(@NonNull String url, @NonNull String path,
40 boolean authEnabled) throws IOException {
41 String connectURL = url;
42 if (!connectURL.endsWith("/"))
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);