如何将简单的文本数据(例如“ Hello World”)发送到PHP服务器

时间:2019-07-04 13:58:17

标签: android

我正在尝试将音频文件和一些文本发送到PHP服务器。我能够将音频文件发送到服务器,但是无法发送文本。

我已经看完这篇文章Sending POST data in Android,并添加了用于发送文本的代码,但是当我尝试上传时,我的应用程序会崩溃。

public class UploadTasks {

    private static int serverResponseCode = 0;
    private static ProgressDialog dialog = null;

    //private static String upLoadServerUri = 
    private static  String filepath = null;

    public static int uploadFile(final String sourceFileUri, Context context, String data) {

        SharedPreferences prefs = context.getSharedPreferences(SHARED_PREF_NAME, MODE_PRIVATE);

        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1024 * 1024;
        OutputStream out = null;

        File sourceFile = new File(sourceFileUri);

        if (!sourceFile.isFile()) {

            Log.e("uploadFile", "Source File not exist :" + filepath);

            return 0;

        } else {
            try {
                FileInputStream fileInputStream = new FileInputStream(
                        sourceFile);
                URL url = new URL(prefs.getString(SHARED_PREF_KEY_URL, null));
                conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true); // Allow Inputs
                conn.setDoOutput(true); // Allow Outputs
                conn.setUseCaches(false); // Don't use a Cached Copy
                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", sourceFileUri);

                out = new BufferedOutputStream(conn.getOutputStream());

                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
                writer.write(data);
                writer.flush();
                writer.close();
                out.close();

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

                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""
                        + sourceFileUri + "\"" + 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);

                }

                // 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();

                Log.i("uploadFile", "HTTP Response is : "
                        + serverResponseMessage + ": " + serverResponseCode);

                // close the streams //
                fileInputStream.close();
                dos.flush();
                dos.close();

            } catch (MalformedURLException ex) {

                ex.printStackTrace();

                Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
            } catch (Exception e) {

                dialog.dismiss();
                e.printStackTrace();

                Log.e("Upload file to server Exception",
                        "Exception : " + e.getMessage(), e);
            }

            return serverResponseCode;
        }
    }
}

以下是我得到的日志记录

2019-07-04 19:32:17.784 32428-32699/com.example.kontrol.mydictation E/Upload file to server Exception: Exception : closed
    java.io.IOException: closed
        at com.android.okhttp.okio.RealBufferedSink$1.write(RealBufferedSink.java:190)
        at java.io.DataOutputStream.writeBytes(DataOutputStream.java:276)
        at com.example.kontrol.mydictation.upload.UploadTasks.uploadFile(UploadTasks.java:84)
        at com.example.kontrol.mydictation.upload.UploadIntentService.onHandleIntent(UploadIntentService.java:18)
        at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:68)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:163)
        at android.os.HandlerThread.run(HandlerThread.java:61)

0 个答案:

没有答案