Вот мой onBackground () asyncTask, который загружает JSON и файл.
@Override
protected String doInBackground(String... strings) {
NewExpenseActivity activity = weakReference.get();
if (activity == null || activity.isFinishing()) {
return null;
}
HttpURLConnection connection = null;
DataOutputStream outputStream;
String twoHyphens = "--";
String boundary = "===" + System.currentTimeMillis();
String end = "\r\n";
String result = "";
try {
BufferedInputStream bufInput = null;
File sourceFile = new File(strings[1]);
URL url = new URL(strings[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setReadTimeout(15000);
connection.setConnectTimeout(15000);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
outputStream = new DataOutputStream(connection.getOutputStream());
HashMap<String, String> parmas = MyUtility.jsonToMap(activity.post);
Iterator<String> keys = parmas.keySet().iterator();
long total_length = sourceFile.length() + parmas.size();
int progress = 0;
activity.runOnUiThread(() -> {
activity.uploadProgress.setMessage("Uploading form data...");
});
while (keys.hasNext()) {
progress++;
String key = keys.next();
String value = parmas.get(key);
publishProgress("" + Math.round((double) progress / total_length * 100)); // sending progress percent to publishProgress
outputStream.writeBytes(twoHyphens + boundary + end);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + end);
outputStream.writeBytes("Content-Type: text/plain" + end);
outputStream.writeBytes(end);
outputStream.writeBytes(value);
outputStream.writeBytes(end);
}
if (!strings[1].equals("none")) {
activity.runOnUiThread(() -> {
activity.uploadProgress.setMessage("Uploading file....");
});
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + "file_list" + "\"; filename=\"" + activity.attach_file + "\"" + end);
// outputStream.writeBytes("Content-Type: " + URLConnection.guessContentTypeFromName(activity.attach_file) + end);
Log.i("response", "" + URLConnection.guessContentTypeFromName(activity.attach_file));
outputStream.writeBytes(end);
int bytesRead = 0;
byte buf[] = new byte[1024];
bufInput = new BufferedInputStream(new FileInputStream(sourceFile));
while ((bytesRead = bufInput.read(buf)) != -1) {
outputStream.write(buf, 0, bytesRead);
progress += bytesRead; // Here progress is total uploaded bytes
Log.i("response", "upload bytes" + ((double) progress / total_length) * 100);
publishProgress("" + Math.round((double) progress / total_length * 100)); // sending progress percent to publishProgress
}
outputStream.writeBytes(end);
activity.runOnUiThread(() -> {
activity.uploadProgress.setMessage("Done."+"\n"+"Wating for server conformation");
});
}
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + end);
outputStream.flush();
outputStream.close();
if (bufInput != null) {
bufInput.close();
}
if (connection.getResponseCode() == 200) {
activity.runOnUiThread(() -> {
Toast.makeText(activity, "success", Toast.LENGTH_SHORT).show();
});
} else {
activity.runOnUiThread(() -> {
Toast.makeText(activity, "failed", Toast.LENGTH_SHORT).show();
});
}
Log.i("response", "response code:\t" + connection.getResponseCode());
//response
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
StringBuilder builder = new StringBuilder();
while ((line = reader.readLine()) != null) {
builder.append(line);
}
result = builder.toString();
reader.close();
} catch (IOException | JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) connection.disconnect();
activity.uploadProgress.setProgress(0);
}
return result;
}
В строках [1] есть путь к файлу при загрузке только JSON, код работает правильноно когда я также добавляю файл, возникает исключение, называемое
java.io.FileNotFoundException:java.io.FileNotFoundException: http://www.weservice.com
, генерируемое через несколько секунд ... в чем проблема, то в моем коде есть какая-то видимая проблема.Чего мне не хватает?