Я пытаюсь загрузить json и файл в веб-сервис, используя многочастную форму.Вот код onBackground asyncTask.Кажется, здесь есть проблема.Что мне здесь не хватает
@Override
protected String doInBackground(String... strings) {
NewExpenseActivity activity = weakReference.get();
if (activity == null || activity.isFinishing()) {
return null;
}
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
String twoHyphens = "--";
String boundary = "XXXXXXXXXXXXXXXXX";
String end = "\r\n";
String result = "";
try {
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.setDoInput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("ENCTYPE", "multipart/form-data");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("file_list",activity.filePath);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + end);
outputStream.writeBytes("Content-Disposition: form-data; name=jsonfile" + end);
outputStream.writeBytes("Content-Type: application/json");
outputStream.writeBytes(end);
outputStream.writeBytes(strings[3]);
outputStream.writeBytes(end);
outputStream.writeBytes(twoHyphens + boundary + end);
outputStream.writeBytes("Content-Disposition: form-data; name=file_list" + "filename=" +activity.filePath);
outputStream.writeBytes(end);
if(activity.image) {
outputStream.writeBytes("Content-Type: image/"+activity.fileType);
}else {
outputStream.writeBytes("Content-Type: application/"+activity.fileType);
}
outputStream.writeBytes(end);
int progress = 0;
int bytesRead = 0;
byte buf[] = new byte[1024];
Log.i("response", "upload length" + sourceFile.length());
BufferedInputStream bufInput = new BufferedInputStream(new FileInputStream(sourceFile));
while ((bytesRead = bufInput.read(buf)) != -1) {
// write output
outputStream.write(buf, 0, bytesRead);
progress += bytesRead; // Here progress is total uploaded bytes
Log.i("response", "upload bytes" + ((double) progress / sourceFile.length()) * 100);
publishProgress("" + Math.round((double) progress / sourceFile.length() * 100)); // sending progress percent to publishProgress
}
outputStream.writeBytes(end);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + end);
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();
});
}
bufInput.close();
outputStream.flush();
outputStream.close();
// Write closing boundary and close stream
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 e) {
e.printStackTrace();
} finally {
if (connection != null) connection.disconnect();
}
}
return result;
}
Я новичок в многочастной загрузке данных, поэтому любые объяснения вместе с ответом высоко ценятся.Другие части кода работают должным образом, потому что он работал в других проектах, я скопировал его просто для того, чтобы не допустить ошибок, где