IOException in Uploading File via HTTP URL Connect

2019-08-30 08:22发布

问题:

I want to upload selected user image into the server but When I want to upload I get IOException

Here is my Code:

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 "";
}

and my error LogCat:

2019-07-01 21:52:14.007 24031-25093/com.pnp.divanEhafez E/fSnd: Starting Http File Sending to URL 2019-07-01 21:52:14.056 24031-25093/com.pnp.divanEhafez E/fSnd: Headers are written 2019-07-01 21:52:14.534 24031-25093/com.pnp.divanEhafez E/fSnd: File Sent, Response: 500 2019-07-01 21:52:14.537 24031-25093/com.pnp.divanEhafez E/fSnd: IO error: http://myURL/?option=webservicehafezop java.io.FileNotFoundException: http://myURL at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:250) at com.pnp.divanEhafez.Network.HttpFileUpload.Sending(HttpFileUpload.java:146) at com.pnp.divanEhafez.Network.HttpFileUpload.Send_Now(HttpFileUpload.java:50) at com.pnp.divanEhafez.UserAccount$3.run(UserAccount.java:181) at java.lang.Thread.run(Thread.java:761)

回答1:

I would like to suggest please set file provider because above Lolipop version need file provider to get access of file system here is the code :

 <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>

Create an xml folder inside the res directory. Add the provider_paths.xml file in it:

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

Now write java code to get file from storage :

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);
}