#android #api #http
#Android #API #http
Вопрос:
я пытался отправить данные из нескольких частей на сервер, этот сервер предназначен для бесплатного размещения файлов, но через его api я не могу размещать свои файлы через приложение для Android Вот URL-адрес бесплатного веб-сайта для размещения файлов: — сайт для размещения файлов
Вот мой код в Android studio:-
File file = new File("/storage/emulated/0/WhatsApp/Media/WhatsApp Audio/AUD-20190504-WA0001.mp3");
String url = "https://srv-store1.gofile.io/uploadFile";
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
Request.Builder builder = new Request.Builder();
builder.url(url);
MultipartBody.Builder bodyBuilder = new MultipartBody.Builder();
bodyBuilder.addFormDataPart("file", file.getName(), RequestBody.create(null, file));
MultipartBody body = bodyBuilder.build();
RequestBody requestBody = ProgressHelper.withProgress(body, new ProgressUIListener() {
@Override
public void onUIProgressStart(long totalBytes) {
super.onUIProgressStart(totalBytes);
Log.e("TAG", "onUIProgressStart:" totalBytes);
}
@Override
public void onUIProgressChanged(long numBytes, long totalBytes, float percent, float speed) {
Log.e("TAG", "=============start===============");
Log.e("TAG", "numBytes:" numBytes);
Log.e("TAG", "totalBytes:" totalBytes);
Log.e("TAG", "percent:" percent);
Log.e("TAG", "speed:" speed);
Log.e("TAG", "============= end ===============");
}
@Override
public void onUIProgressFinish() {
super.onUIProgressFinish();
Log.e("TAG", "onUIProgressFinish:");
Toast.makeText(getApplicationContext(), "结束上传", Toast.LENGTH_SHORT).show();
}
});
builder.post(requestBody);
okhttp3.Call call = okHttpClient.newCall(builder.build());
call.enqueue(new okhttp3.Callback() {
@Override
public void onFailure(okhttp3.Call call, IOException e) {
Log.e("TAG", "=============onFailure===============");
e.printStackTrace();
}
@Override
public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
Log.e("TAG", "=============onResponse===============");
Log.e("TAG", "request headers:" response.request().headers());
Log.e("TAG", "response headers:" response.body().string());
}
});
и для этого в Android используется библиотека: -«реализация ‘io.github.lizhangqu: coreprogress: 1.0.2‘»
поэтому, когда я запускаю этот код, возникает эта ошибка: —Неподдерживаемый тип содержимого: составные / смешанные;
Я не получаю ни малейшего представления о том, как все это решить, даже после просмотра множества ответов stackoverflow и самостоятельного тестирования.
Комментарии:
1. Пожалуйста, дайте ссылку на информацию об API gofile.
2. Вы можете установить другой тип контента.
Ответ №1:
Итак, наконец, я нашел свое решение с помощью приведенного ниже кода, надеюсь, это может помочь другим.
public int uploadFile(String sourceFileUri) {
int serverResponseCode=0;
String fileName="/storage/emulated/0/WhatsApp/Media/WhatsApp Audio/AUD-20190504-WA0001.mp3";
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "rn";
String twoHyphens = "--";
String boundary = "------hellojosh";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(fileName);
Log.e("appTag", "Uploading: sourcefileURI, " fileName);
if (!sourceFile.isFile()) {
Log.e("uploadFile", "Source File not exist :" appSingleton.getInstance().photouri);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :");
}
});
return 0;
}
else{
try{
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL("https://srv-store4.gofile.io/uploadFile");
Log.v("appTag",url.toString());
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a Cached Copy
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" boundary);
conn.setRequestProperty("file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens boundary lineEnd);
dos.writeBytes("Content-Disposition: form-data; name="file";filename="" fileName """ lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
Log.i("appTag","->");
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens boundary twoHyphens lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage().toString();
Log.i("appTag", "HTTP Response is : " serverResponseMessage ": " serverResponseCode);
// ------------------ read the SERVER RESPONSE
DataInputStream inStream;
try {
inStream = new DataInputStream(conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null) {
Log.e("appTag", "SOF Server Response" str);
}
inStream.close();
}
catch (IOException ioex) {
Log.e("appTag", "SOF error: " ioex.getMessage(), ioex);
}
//close the streams
fileInputStream.close();
dos.flush();
dos.close();
if(serverResponseCode == 200){
//Do something
}
//END IF Response code 200
dialog.dismiss();
}
//END TRY - FILE READ
catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("appTag", "UL error: " ex.getMessage(), ex);
}
//CATCH - URL Exception
catch (Exception e) {
e.printStackTrace();
Log.e("Upload file to server Exception", "Exception : " e.getMessage(), e);
}
//after try
return serverResponseCode;
}
//END ELSE, if file exists.
}
Хотя мне нужно было закомментировать некоторые вещи в этом коде, но это был лучший ответ для меня, я также организовал код для загрузки файла с сервера с помощью Android Download Manager, но это не решает этот вопрос.