IOException при загрузке файла через соединение HTTP URL - PullRequest
0 голосов
/ 02 июля 2019

Я хочу загрузить выбранное изображение пользователя на сервер, но когда я хочу загрузить , я получаю IOException

Вот мой код:

String Sending(List<String> MyParams, List<String> MyParamsValue) {

    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    String Tag = "fSnd";
    try {
        Log.e(Tag, "Starting Http File Sending to URL");

        // Open a HTTP connection to the URL
        HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection();

        // Allow Inputs
        conn.setDoInput(true);

        // Allow Outputs
        conn.setDoOutput(true);

        // Don't use a cached copy.
        conn.setUseCaches(false);

        // Use a post method.
        conn.setRequestMethod("POST");

        conn.setRequestProperty("Connection", "Keep-Alive");
        // ////////////////////////////////////////////////////////////////////

        conn.setRequestProperty("User-Agent", ctx.getResources().getString(com.pnp.divanEhafez.R.string.app_name));
        // ////////////////////////////////////////////////////////////////////

        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

        for (int o = 0; o < MyParams.size(); o++) {
            if (MyParamsValue.get(o).trim().length() >= 1) {
                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"" + MyParams.get(o).toString() + "\""
                        + lineEnd);
                dos.writeBytes(lineEnd);

                dos.write(MyParamsValue.get(o).getBytes("UTF-8"));
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + lineEnd);
            }
        }

        for (int f = 0; f < fileInputStream.size(); f++) {
            // if (f == 0)
            // dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
            // + "thumb.jpg"
            // + "\"" + lineEnd);
            // else
            String FileName = MediaListName.get(f).substring(MediaListName.get(f).lastIndexOf("/") + 1);
            System.out.println(FileName);
            dos.writeBytes("Content-Disposition: form-data; name=\"tfile" + String.valueOf(f) + "\";filename=\""
                    + FileName + "\"" + lineEnd);

            dos.writeBytes(lineEnd);

            Log.e(Tag, "Headers are written");

            // create a buffer of maximum size
            int bytesAvailable = fileInputStream.get(f).available();

            int maxBufferSize = 1024;
            int bufferSize = Math.min(bytesAvailable, maxBufferSize);
            byte[] buffer = new byte[bufferSize];

            // read file and write it into form...
            int bytesRead = fileInputStream.get(f).read(buffer, 0, bufferSize);

            while (bytesRead > 0) {
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.get(f).available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.get(f).read(buffer, 0, bufferSize);
            }
            dos.writeBytes(lineEnd);

            if ((f + 1) < fileInputStream.size())
                dos.writeBytes(twoHyphens + boundary + lineEnd);
            else
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // close streams
            fileInputStream.get(f).close();

        }

        dos.close();
        Log.e(Tag, "File Sent, Response: " + String.valueOf(conn.getResponseCode()));


        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

        // retrieve the response from server
        int ch;

        StringBuffer b = new StringBuffer();
        while ((ch = reader.read()) != -1) {
            b.append((char) ch);
        }
        String s = b.toString();
        Log.i("Response", s);
        dos.close();
        conn.disconnect();

        return s;

    } catch (MalformedURLException ex) {
        Log.e(Tag, "URL error: " + ex.getMessage(), ex);
        TrackHelper.trackFatalException(ctx, ex);

    } catch (IOException ioe) {
        Log.e(Tag, "IO error: " + ioe.getMessage(), ioe);
        TrackHelper.trackFatalException(ctx, ioe);
    }
    return "";
}

и моя ошибка LogCat:

2019-07-01 21: 52: 14.007 24031-25093 / com.pnp.divanEhafez E / fSnd: запуск отправки файла Http на URL 2019-07-01 21:52: 14.056 24031-25093 / com.pnp.divanEhafez E / fSnd: записаны заголовки 2019-07-01 21: 52: 14.534 24031-25093 / com.pnp.divanEhafez E / fSnd: отправлено файлов, ответ: 500 2019-07-01 21: 52: 14.537 24031-25093 / com.pnp.divanEhafez E / fSnd: ошибка ввода-вывода: http://myURL/?option=webservicehafezop java.io.FileNotFoundException: http://myURL на com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream (HttpURLConnectionImpl.java:250) при com.pnp.divanEhafez.Network.HttpFileUpload.Sending (HttpFileUpload.java:146) в com.pnp.divanEhafez.Network.HttpFileUpload.Send_Now (HttpFileUpload.java:50) в com.pnp.divanEhafez.UserAccount $ 3.run (UserAccount.java:181) в java.lang.Thread.run (Thread.java:761)

1 Ответ

0 голосов
/ 02 июля 2019

Я хотел бы предложить, пожалуйста, установить файловый провайдер, потому что выше версии Lolipop нужен файловый провайдер, чтобы получить доступ к файловой системе, вот код:

 <provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="com.package.name.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

Создайте папку xml внутри директории res.Добавьте в него файл provider_paths.xml:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

Теперь напишите код Java, чтобы получить файл из хранилища:

private String getImageFromFilePath(Intent data) {
boolean isCamera = data == null || data.getData() == null;

if (isCamera) return getCaptureImageOutputUri().getPath();
 else return getPathFromURI(data.getData());

}

public String getImageFilePath(Intent data) {
    return getImageFromFilePath(data);
}

private String getPathFromURI(Uri contentUri) {
    String[] proj = {MediaStore.Audio.Media.DATA};
    Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}
...