(Context context, File file, String apiKey)
| 94 | } |
| 95 | |
| 96 | static String upload(Context context, File file, String apiKey) throws IOException, JSONException { |
| 97 | // Get upload URL |
| 98 | Pair<Integer, String> response = call(context, "api/v3/files/upload_url", apiKey); |
| 99 | if (response.first != HttpsURLConnection.HTTP_OK) |
| 100 | throw new FileNotFoundException(response.second); |
| 101 | JSONObject jurl = new JSONObject(response.second); |
| 102 | String upload_url = jurl.getString("data"); |
| 103 | |
| 104 | // Upload file |
| 105 | String boundary = "----FairEmail." + System.currentTimeMillis(); |
| 106 | |
| 107 | URL url = new URL(upload_url); |
| 108 | Log.i("VT upload url=" + url); |
| 109 | HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); |
| 110 | connection.setRequestMethod("POST"); |
| 111 | connection.setDoOutput(true); |
| 112 | connection.setReadTimeout(VT_TIMEOUT * 1000); |
| 113 | connection.setConnectTimeout(VT_TIMEOUT * 1000); |
| 114 | ConnectionHelper.setUserAgent(context, connection); |
| 115 | connection.setRequestProperty("x-apikey", apiKey); |
| 116 | connection.setRequestProperty("Accept", "application/json"); |
| 117 | connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); |
| 118 | connection.connect(); |
| 119 | |
| 120 | try { |
| 121 | OutputStream os = connection.getOutputStream(); |
| 122 | |
| 123 | PrintWriter writer = new PrintWriter(new OutputStreamWriter(os)); |
| 124 | writer |
| 125 | .append("--").append(boundary).append("\r\n") |
| 126 | .append("Content-Disposition: form-data;") |
| 127 | .append(" name=\"file\";") |
| 128 | .append(" filename=\"").append(file.getName()).append("\"").append("\r\n") |
| 129 | .append("Content-Type: application/octet-stream").append("\r\n") |
| 130 | .append("Content-Transfer-Encoding: binary").append("\r\n") |
| 131 | .append("\r\n") |
| 132 | .flush(); |
| 133 | |
| 134 | try (InputStream is = new FileInputStream(file)) { |
| 135 | Helper.copy(is, os); |
| 136 | } |
| 137 | |
| 138 | os.flush(); |
| 139 | |
| 140 | writer |
| 141 | .append("\r\n") |
| 142 | .append("--").append(boundary).append("--").append("\r\n") |
| 143 | .flush(); |
| 144 | |
| 145 | writer.close(); |
| 146 | |
| 147 | int status = connection.getResponseCode(); |
| 148 | if (status != HttpsURLConnection.HTTP_OK) { |
| 149 | String error = "Error " + status + ": " + connection.getResponseMessage(); |
| 150 | try { |
| 151 | InputStream is = connection.getErrorStream(); |
| 152 | if (is != null) |
| 153 | error += "\n" + Helper.readStream(is); |
nothing calls this directly
no test coverage detected