]> git.ipfire.org Git - thirdparty/strongswan.git/blob - src/frontends/android/app/src/main/java/org/strongswan/android/logic/SimpleFetcher.java
android: Add support to POST data via SimpleFetcher
[thirdparty/strongswan.git] / src / frontends / android / app / src / main / java / org / strongswan / android / logic / SimpleFetcher.java
1 /*
2 * Copyright (C) 2017 Tobias Brunner
3 * HSR Hochschule fuer Technik Rapperswil
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * for more details.
14 */
15
16 package org.strongswan.android.logic;
17
18 import android.support.annotation.Keep;
19
20 import java.io.BufferedOutputStream;
21 import java.io.ByteArrayOutputStream;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.OutputStream;
25 import java.net.HttpURLConnection;
26 import java.net.URL;
27
28 @Keep
29 public class SimpleFetcher
30 {
31 public static byte[] fetch(String uri, byte[] data, String contentType) throws IOException
32 {
33 URL url = new URL(uri);
34 HttpURLConnection conn = (HttpURLConnection)url.openConnection();
35 conn.setConnectTimeout(10000);
36 conn.setReadTimeout(10000);
37 try
38 {
39 if (contentType != null)
40 {
41 conn.setRequestProperty("Content-Type", contentType);
42 }
43 if (data != null)
44 {
45 conn.setDoOutput(true);
46 conn.setFixedLengthStreamingMode(data.length);
47 OutputStream out = new BufferedOutputStream(conn.getOutputStream());
48 out.write(data);
49 out.close();
50 }
51 return streamToArray(conn.getInputStream());
52 }
53 finally
54 {
55 conn.disconnect();
56 }
57 }
58
59 private static byte[] streamToArray(InputStream in) throws IOException
60 {
61 ByteArrayOutputStream out = new ByteArrayOutputStream();
62 byte[] buf = new byte[1024];
63 int len;
64
65 try
66 {
67 while ((len = in.read(buf)) != -1)
68 {
69 out.write(buf, 0, len);
70 }
71 return out.toByteArray();
72 }
73 catch (IOException e)
74 {
75 e.printStackTrace();
76 }
77 finally
78 {
79 in.close();
80 }
81 return null;
82 }
83 }