web-dev-qa-db-ja.com

Android- POST multipart form data

ビデオと電子メールや名前などのデータを含むマルチパートフォームを送信したいと思います。以下は私のコードであり、機能しません、サーバーからの応答がありません

File file =new File(VideoPath);
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("Name", "LDGHT"));
            nameValuePairs.add(new BasicNameValuePair("Email", "[email protected]"));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            httppost.setEntity(new FileEntity(file, "video/mp4"));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
17
Dev

マルチパートデータの送信について私の投稿を確認する マルチパートを使用してサーバーにデータを送信する ..

こちらも参考にしてください Link

new Task_Finder().execute();

ビデオファイルをサーバーにアップロード:

    public class Task_Finder extends AsyncTask<Void, Void, Void> {
    private final ProgressDialog dialog = new ProgressDialog(Facebook_Post_View.this);
    // can use UI thread here
    protected void onPreExecute() {
        this.dialog.setMessage("Loading...");
        this.dialog.setCancelable(false);
        this.dialog.show();
    }
    @Override
    protected Void doInBackground(Void... arg0) {
        // TODO Auto-generated method stub
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        DataInputStream inStream = null;
        String existingFileName = file_path;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary =  "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1*1024*1024;
        String urlString = "YOUR PHP LINK FOR UPLOADING IMAGE";
        try{
            //------------------ CLIENT REQUEST
            FileInputStream fileInputStream = new FileInputStream(new File(existingFileName) );
            // open a URL connection to the Servlet
            URL url = new URL(urlString);
            // 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);
            // Use a post method.
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
            dos = new DataOutputStream( conn.getOutputStream() );
            dos.writeBytes(twoHyphens + boundary + lineEnd);

            dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + upload_file_name + "\"" + lineEnd); // uploaded_file_name is the Name of the File to be uploaded
            dos.writeBytes(lineEnd);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            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);
            }
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            fileInputStream.close();
            dos.flush();
            dos.close();
        }
        catch (MalformedURLException ex){
            Log.e("Debug", "error: " + ex.getMessage(), ex);
        }
        catch (IOException ioe){
            Log.e("Debug", "error: " + ioe.getMessage(), ioe);
        }
        //------------------ read the SERVER RESPONSE
        try {
            inStream = new DataInputStream ( conn.getInputStream() );
            String str;
            while (( str = inStream.readLine()) != null){
                Log.e("Debug","Server Response "+str);
                reponse_data=str;
            }
            inStream.close();
        }
        catch (IOException ioex){
            Log.e("Debug", "error: " + ioex.getMessage(), ioex);
        }
       return null;
    }

    @Override
    protected void onPostExecute(Void result) {

        if (this.dialog.isShowing()) {
            this.dialog.dismiss();
        }
    }
}
24
Venky

残念ながら、Venkyのコードを使用することはできませんでした。 2日後、私は最終的に自分の解決策を見つけ、それが同じ問題を抱えている人たちに役立つことを願っています。このコードは私の構造に基づいているため、自由にコードを変更してください。注:bitmapProfileImageは、ビットマップイメージ(Bitmap bitmapProfileImage;)を保持するグローバル変数です。

public class ContentDownloader {

        public static String getHttpPutContent(String url, String token, MultipartEntity multipartEntity) {

            try {
                HttpClient httpClient = new DefaultHttpClient();
                HttpPut put = new HttpPut(url);
                put.setHeader("token", token);
    //            Log.i(TAG, "Token=> " + token);
                Log.i(TAG, "Try to open=> " + url);

                MultipartEntity reqEntity = multipartEntity;
                put.setEntity(reqEntity);

                HttpResponse httpResponse = httpClient.execute(put);
                int statusCode = httpResponse.getStatusLine().getStatusCode();
                Log.i(TAG, "Connection code: " + statusCode);

                HttpEntity entity = httpResponse.getEntity();
                String serverResponse = EntityUtils.toString(entity);
                Log.i(TAG, "Server response=> " + serverResponse);

                if(!isStatusOk(statusCode))
                    return null;

                return serverResponse;

            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        } 

        /**
         *
         * @param statusCode
         * @return True if connection code is 2xx, False otherwise.
         */
        private static boolean isStatusOk(int statusCode) {
            if((statusCode >= HttpURLConnection.HTTP_OK)  &&  (statusCode <= HttpURLConnection.HTTP_PARTIAL))
                return true;

            return false;
        }
}

したがって、アクティビティ/フラグメントにはAsyncTaskクラスが必要です。 doInBackgroundメソッド内に次のコードを追加します。

        @Override
        protected Integer doInBackground(Void... params) {
            String content = "";
            String url = LinkManager.getUserProfileUrl();

            Person person = SpStorage.getPersonInfo(context);

                String imgPath = SpStorage.getProfilePicPath(context);
                String imgName = imgPath.substring(imgPath.lastIndexOf("/") + 1);

                if(bitmapProfileImage == null) {
                    Log.i(TAG, "bitmap is null. Try to get it from profile pic directory...");
                    String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
                            File.separator + ImageDownloader.DIRECTORY_NAME + File.separator + PROFILE_PICS;
                    imgPath = new File(file_path, imgName).getAbsolutePath();
                    bitmapProfileImage = BitmapFactory.decodeFile(imgPath);
                }

                if(bitmapProfileImage != null) {
                    Log.i(TAG, "Image address: " + imgPath);

                    try {
                        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                        reqEntity.addPart("first_name", new StringBody(person.getName()));
                        reqEntity.addPart("last_name", new StringBody(""));
                        reqEntity.addPart("email",new StringBody(person.getEmail()));
                        reqEntity.addPart("birthday", new StringBody(person.getBirthDay()));
                        reqEntity.addPart("gender", new StringBody(person.getGender(person.getGender())));
                        reqEntity.addPart("orientation", new StringBody(person.getOrientation(person.getGender(), person.getLookingFor())));
                        reqEntity.addPart("relationship_status", new StringBody(person.getStatus(person.getStatus())));
                        reqEntity.addPart("city", new StringBody(person.getCity()));
                        reqEntity.addPart("about", new StringBody(person.getAboutMe()));
                        reqEntity.addPart("device_type", new StringBody("Android"));

                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        bitmapProfileImage.compress(Bitmap.CompressFormat.PNG, 0, bos);
                        byte[] data = bos.toByteArray();
                        ByteArrayBody bab = new ByteArrayBody(data, "profilePic.png");
                        reqEntity.addPart("photo", bab);

                        content = ContentDownloader.getHttpPutContent(url, SpStorage.getToken(context), reqEntity);
                    }
                    catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                    }
                } else
                    Log.e(TAG, "Image not found :(");


            if(!TextUtils.isEmpty(content)) {
                return 0; // registration successful
            }

            return -1;
        }

最後に、MultipartEntityを使用するには、4つのjarファイルをダウンロードする必要があります。 1つは Apache-mime4j で、残りは httpclient、httpcoreおよびhttpmime です。 jarファイルを抽出して、プロジェクトの./libsフォルダにコピー/貼り付けする必要があります。

別の完全なサンプルを使用

5
Hesam

Apache httpライブラリを使用して、ポストでイメージを送信するための私の解決策があります(私はより簡単であることを願っています)(ここで非常に重要なのは、境界の追加です。接続しないと機能しません)。私はそれがそのような状況で役立つことを願っています:

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
            byte[] imageBytes = baos.toByteArray();

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(StaticData.AMBAJE_SERVER_URL + StaticData.AMBAJE_ADD_AMBAJ_TO_GROUP);

            String boundary = "-------------" + System.currentTimeMillis();

            httpPost.setHeader("Content-type", "multipart/form-data; boundary="+boundary);

            ByteArrayBody bab = new ByteArrayBody(imageBytes, "pic.png");
            StringBody sbOwner = new StringBody(StaticData.loggedUserId, ContentType.TEXT_PLAIN);
            StringBody sbGroup = new StringBody("group", ContentType.TEXT_PLAIN);

            HttpEntity entity = MultipartEntityBuilder.create()
                    .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                    .setBoundary(boundary)
                    .addPart("group", sbGroup)
                    .addPart("owner", sbOwner)
                    .addPart("image", bab)
                    .build();

            httpPost.setEntity(entity);

            try {
                HttpResponse response = httpclient.execute(httpPost);
                ...then reading response
3
Krystian