728x90

이미지 파일 전송시 서버에서 구현할 PHP 소스는 다음과 같다.

개인 프로필 사진을 업로드할 경우의 수정사항이다.


<?php
if(isset($_POST['idx']) && $_POST['idx']>0){
    $idx=$_POST['idx'];

    $file_path='./photos/'.$idx.'.jpg'; //이미지화일명은 인덱스번호로 지정
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
        $result = array("result" => "success");
    } else{
        $result = array("result" => "error");
    }
    echo json_encode($result);
}
?>


안드로이드 수정사항

Button btn_UploadPhoto = (Button) findViewById(R.id.btn_Upload); // 사진 업로드
btn_UploadPhoto.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (TextUtils.isEmpty(imagePath)) {
            Toast.makeText(getApplicationContext(), "업로드할 사진을 선택해주세요", Toast.LENGTH_SHORT).show();
        } else {
            if (NetworkHelper.checkConnection(mContext)) { // 인터넷 연결 체크
                Log.d("Photo", "Photo Upload Task Start");
                String ImageUploadURL = Value.IPADDRESS + "/upload.php";
                SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
                String idx = pref.getString("idx", "");
                ImageUploadTask imageUploadTask = new ImageUploadTask();
                imageUploadTask.execute(ImageUploadURL, imagePath, idx);
            } else {
                Toast.makeText(mContext, "인터넷 연결을 확인하세요", Toast.LENGTH_LONG).show();
            }
        }
    }
});


 class ImageUploadTask extends AsyncTask<String, Integer, Boolean> {
    ProgressDialog progressDialog; // API 26에서 deprecated

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("이미지 업로드중....");
        progressDialog.show();
    }

    @Override
    protected Boolean doInBackground(String... params) {
        try {
            JSONObject jsonObject = JSONParser.uploadImage(params[0],params[1],params[2]);
            if (jsonObject != null)
                return jsonObject.getString("result").equals("success");

        } catch (JSONException e) {
            Log.i("TAG", "Error : " + e.getLocalizedMessage());
        }
        return false;
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);
        if (progressDialog != null)
            progressDialog.dismiss();

        if (aBoolean){
            Toast.makeText(getApplicationContext(), "파일 업로드 성공", Toast.LENGTH_LONG).show();
            // 임시 파일 삭제 (카메라로 사진 촬영한 이미지)
            if(mImageCaptureUri != null){
                File file = new File(mImageCaptureUri.getPath());
                if(file.exists()) {
                    file.delete();
                }
                mImageCaptureUri = null;
            }
            imagePath = null;
        }  else{
            Toast.makeText(getApplicationContext(), "파일 업로드 실패", Toast.LENGTH_LONG).show();
        }

    }
}

 public class JSONParser {

    public static JSONObject uploadImage(String imageUploadUrl, String sourceImageFile, String idx) {
        final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/*");

        try {
            File sourceFile = new File(sourceImageFile);
            Log.d("TAG", "File...::::" + sourceFile + " : " + sourceFile.exists());
            String filename = sourceImageFile.substring(sourceImageFile.lastIndexOf("/")+1);

            // OKHTTP3
            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("uploaded_file", filename, RequestBody.create(MEDIA_TYPE_PNG, sourceFile))
                    .addFormDataPart("idx", idx)
                    .build();

            Request request = new Request.Builder()
                    .url(imageUploadUrl)
                    .post(requestBody)
                    .build();

            OkHttpClient client = new OkHttpClient();
            Response response = client.newCall(request).execute();
            if (response != null) {
                if (response.isSuccessful()) {
                    String res = response.body().string();
                    Log.e("TAG", "Success : " + res);
                    return new JSONObject(res);
                }
            }
        } catch (UnknownHostException | UnsupportedEncodingException e) {
            Log.e("TAG", "Error: " + e.getLocalizedMessage());
        } catch (Exception e) {
            Log.e("TAG", "Other Error: " + e.getLocalizedMessage());
        }
        return null;
    }
}


블로그 이미지

Link2Me

,
728x90

안드로이드 스튜디오에서 사진촬영 및 특정부분 이미지를 CROP 해서 업로드하는 법과 갤러리(앨범)에서 사진을 선택해서 업로드하는 걸 테스트하고 있다.


 삼성 갤럭시 S7 (7.0)

 사진 촬영후 CROP 전송 OK,

 갤러리 사진 선택후 CROP하면 기존 파일을 덮어쓰는 현상(해결 필요)

 삼성 갤럭시 A5 (6.0.1)

 사진 촬영후 CROP 전송 OK, 갤러리 CROP 후 전송 OK

 삼성 갤럭시 S4 (5.0.1)

 사진 촬영후 CROP 전송 OK, 갤러리 CROP 후 전송 OK


안드로이드 7.0 이상 운영체제에서 문제가 있는 것인지 집중적인 테스트가 필요할 거 같다.

지난번 테스트보다는 기능이 개선되었지만, 좀 더 보완이 필요하다.

7.0 에서 테스트한 결과는 이미지를 축소 저장하는 saveCropImage 메소드가 없이 자체적으로(?) 이미지를 축소하기 때문에 원본 갤러리 파일에 문제가 생기는 거 같다.

사진 촬영후 전송할 경우 같은 myphoto.jpg 로 저장하도록 해서 문제 없이 서버에 축소된 이미지가 업로드된다.

문제는 갤러리 사진을 업로드할 경우 CROP 까지는 잘되는데, CROP 한 후에 원본 이미지를 훼손하는 문제가 생긴다. 갤럭시 S4, A5에서는 정상동작한다. 코드 상으로도 정상 동작되어야 맞는거 같은데.....

7.0 에서 뭔가 내가 놓치는 것이 뭘까??? 좀 더 찾아보고 해결해보련다.


음.... 확인해보니 Build.VERSION.SDK_INT 가 24이상인 경우에는 다른 방법으로 구현해야 하더라.

일일이 로그를 찍어가면서 확인해보니, CROP 이후에 값 자체가 넘어오지 않고 그냥 임시로 생성한 파일만 지정한 폴더(디렉토리)에 저장되는 걸 확인했다.

내가 구현한 방식은 한마디로 편법으로 7.0 에서 동작되었던 것이다.

임시로 저장된 파일을 다시 읽어서 그 파일을 서버로 업로드하는 거다.


 package com.tistory.link2me.imageupload;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;
import com.tistory.link2me.common.BackPressHandler;
import com.tistory.link2me.common.JSONParser;
import com.tistory.link2me.common.NetworkHelper;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class PhotoActivity extends Activity {
    Context mContext;

    private static final int PICK_FROM_CAMERA = 0; //카메라 촬영으로 사진 가져오기
    private static final int PICK_FROM_ALBUM = 1; //앨범에서 사진 가져오기
    private static final int CROP_FROM_CAMERA = 2; // 가져온 사진을 자르기 위한 변수
    private static final int PICK_FROM_File = 3; //앨범에서 사진 가져오기(원본 올리기)

    private static Uri mImageCaptureUri; // Stactic 으로 설정해야 에러 발생하지 않음.
    private String imagePath;
    private ImageView imageView;
    private Bitmap photoBitmap;
    String saveFolderName = "cameraTemp";
    File mediaFile = null;
    String saveFileName = "myphoto.jpg";

    ProgressDialog mProgressDialog;
    private BackPressHandler backPressHandler;

    private String[] permissions = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO
    };
    private static final int MULTIPLE_PERMISSIONS = 101;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo);
        mContext = this.getBaseContext();
        backPressHandler = new BackPressHandler(this); // 뒤로 가기 버튼 이벤트

        System.out.println("프로세스당 메모리 용량 : " + ((ActivityManager)getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass());
        System.out.println("largeHeap 크기 : " + ((ActivityManager)getSystemService(Context.ACTIVITY_SERVICE)).getLargeMemoryClass());
        System.out.println("패키지 설치 경로 : " + getApplicationContext().getFilesDir().getAbsolutePath().replace("files", ""));

        checkPermissions();
        initView();
    }

    private void initView() {
        imageView = (ImageView) findViewById(R.id.croppedImageView);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(PhotoActivity.this);
                builder.setMessage("업로드할 이미지 선택");
                DialogInterface.OnClickListener cameraListener = new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        doTakePhotoAction();
                    }
                };

                DialogInterface.OnClickListener albumListener = new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getGallery(); // 갤러리(앨범)에서 이미지 가져오기
                    }
                };

                DialogInterface.OnClickListener cancelListener = new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }

                };
                builder.setTitle("업로드할 이미지 선택");
                builder.setPositiveButton("사진촬영", cameraListener);
                builder.setNeutralButton("앨범선택", albumListener);
                builder.setNegativeButton("취소", cancelListener);
                builder.show();

            }
        });

        Button btn_UploadPhoto = (Button) findViewById(R.id.btn_Upload);
        btn_UploadPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(imagePath)) {
                    Toast.makeText(getApplicationContext(), "업로드할 사진을 선택해주세요", Toast.LENGTH_SHORT).show();
                } else {
                    if (NetworkHelper.checkConnection(mContext)) { // 인터넷 연결 체크
                        Log.d("Photo", "Photo Upload Task Start");
                        String ImageUploadURL = Value.IPADDRESS + "/upload.php";
                        ImageUploadTask imageUploadTask = new ImageUploadTask();
                        imageUploadTask.execute(ImageUploadURL, imagePath);
                    } else {
                        Toast.makeText(mContext, "인터넷 연결을 확인하세요", Toast.LENGTH_LONG).show();
                    }
                }
            }
        });

    }

    private Boolean isAirModeOn() {
        Boolean isAirplaneMode;
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1){
            isAirplaneMode = Settings.System.getInt(getContentResolver(),
                    Settings.System.AIRPLANE_MODE_ON, 0) == 1;
        }else{
            isAirplaneMode = Settings.Global.getInt(getContentResolver(),
                    Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
        }
        return isAirplaneMode;
    }

    /**
     * 카메라에서 사진 촬영
     */
    private void doTakePhotoAction() {  // 카메라 앱을 이용하여 사진 찍기
        // Intent를 사용하여 안드로이드에서 기본적으로 제공해주는 카메라를 이용하는 방법 이용
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 이미지가 저장될 파일은 카메라 앱이 구동되기 전에 세팅해서 넘겨준다.
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, getImageUri(saveFileName)); // null
        cameraIntent.putExtra("return-data", true);
        startActivityForResult(cameraIntent, PICK_FROM_CAMERA); // 7.0 에서는 에러가 발생함. (API26 으로 컴파일 한 경우)
    }

    // 사진 선택을 위해 갤러리를 호출
    private void getGallery() {
        // File System.
        final Intent galleryIntent = new Intent();
        galleryIntent.setType("image/*"); // 이미지 파일 호출
        galleryIntent.setAction(Intent.ACTION_PICK);

        // Chooser of file system options.
        final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Image");
        galleryIntent.setType(MediaStore.Images.Media.CONTENT_TYPE);
        //startActivityForResult(chooserIntent, PICK_FROM_File);
        startActivityForResult(chooserIntent, PICK_FROM_ALBUM);
    }

    private Uri getImageUri(String saveFile) {
        // 임시로 사용할 파일의 경로를 생성
        File mediaStorageDir = new File(Environment.getExternalStorageDirectory() + "/DCIM", saveFolderName);
        if (! mediaStorageDir.exists()){
            if (! mediaStorageDir.mkdirs()){
                Log.d("MyCameraApp", "failed to create directory");
                return null;
            }
        }

        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        if(saveFile != null){
            mediaFile = new File(mediaStorageDir.getPath() + File.separator + saveFile);
        } else {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator + "pic_"+ timeStamp + ".jpg");
        }
        mImageCaptureUri = Uri.fromFile(mediaFile);
        imagePath = mImageCaptureUri.getPath();
        Log.e("mImageCaptureUri : ", mImageCaptureUri.toString());
        Log.e("imagePath : ", imagePath);

        return mImageCaptureUri;
    }

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

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode != Activity.RESULT_OK) return;
        switch (requestCode){
            case PICK_FROM_ALBUM: {
                mImageCaptureUri = data.getData();
                Log.e("앨범이미지 CROP",mImageCaptureUri.getPath().toString());
                imagePath = getRealPathFromURI(mImageCaptureUri); // 실제 파일이 존재하는 경로
                Log.e("앨범이미지 경로",imagePath);
            }

            case PICK_FROM_CAMERA: {

                // 이미지를 가져온 이후의 리사이즈할 이미지 크기를 결정
                Intent intent = new Intent("com.android.camera.action.CROP");
                intent.setDataAndType(mImageCaptureUri, "image/*");

                // CROP할 이미지를 125*170 크기로 저장
                intent.putExtra("outputX", 125); // CROP한 이미지의 x축 크기
                intent.putExtra("outputY", 170); // CROP한 이미지의 y축 크기
                intent.putExtra("aspectX", 1); // CROP 박스의 X축 비율
                intent.putExtra("aspectY", 1); // CROP 박스의 Y축 비율
                intent.putExtra("scale", true);
                intent.putExtra("return-data", true);

                startActivityForResult(intent, CROP_FROM_CAMERA); // CROP_FROM_CAMERA case문 이동
                break;
            }

            case CROP_FROM_CAMERA:  {
                // CROP 된 이후의 이미지를 넘겨 받음
                final Bundle extras = data.getExtras();

                // CROP 된 이미지를 저장하기 위한 File 경로 설정
                String filePath = getImageUri(saveFileName).getPath();
                Log.e("mImageCaptureUri : ", "Croped " + mImageCaptureUri.toString());

                imagePath = filePath;

                if(extras != null) {
                    //photoBitmap = extras.getParcelable("data"); // CROP된 BITMAP
                    photoBitmap = (Bitmap)data.getExtras().get("data"); // CROP된 BITMAP
                    // 레이아웃의 이미지칸에 CROP된 BITMAP을 보여줌
                    saveCropImage(photoBitmap,imagePath); //  CROP 된 이미지를 외부저장소, 앨범에 저장한다.
                    // sendBroadcast를 통해 Crop된 사진을 앨범에 보이도록 갱신한다.
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        sendBroadcast(new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(mediaFile)) );
                    } else {
                        sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
                    }
                }

                Picasso.with(mContext).load(new File(imagePath))
                        .into(imageView); // 피카소 라이브러를 이용하여 선택한 이미지를 imageView에 출력

                break;
            }
            case PICK_FROM_File: {
                // URI 정보를 이용하여 이미지(사진) 정보를 가져온다.
                if (data == null) {
                    Toast.makeText(mContext, "Unable to Pickup Image", Toast.LENGTH_SHORT).show();
                    return;
                }
                Uri selectedImageUri = data.getData();
                Log.e("IMAGE SEL", "" + selectedImageUri);
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                Cursor cursor = getContentResolver().query(selectedImageUri, filePathColumn, null, null, null);

                if (cursor != null) {
                    cursor.moveToFirst();

                    imagePath = cursor.getString(cursor.getColumnIndex(filePathColumn[0]));
                    Log.e("IMAGE SEL imagePath : ", imagePath);                 

                    Picasso.with(mContext).load(new File(imagePath))
                            .into(imageView); // 피카소 라이브러를 이용하여 선택한 이미지를 imageView에 출력
                    cursor.close();

                }

                break;
            }
        }

    }

    // Bitmap 을 저장하는 메소드
    private void saveCropImage(Bitmap bitmap, String filePath) {
        //read image file
        File copyFile = new File(filePath);
        BufferedOutputStream bos = null;
        try {
            copyFile.createNewFile();
            int quality = 100;
            bos = new BufferedOutputStream(new FileOutputStream(copyFile));
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos);
            // 이미지가 클 경우 OutOfMemoryException 발생이 예상되어 압축
            bos.flush();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class ImageUploadTask extends AsyncTask<String, Integer, Boolean> {
        ProgressDialog progressDialog; // API 26에서 deprecated

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = new ProgressDialog(PhotoActivity.this);
            progressDialog.setMessage("이미지 업로드중....");
            progressDialog.show();
        }

        @Override
        protected Boolean doInBackground(String... params) {
            try {
                JSONObject jsonObject = JSONParser.uploadImage(params[0],params[1]);
                if (jsonObject != null)
                    return jsonObject.getString("result").equals("success");

            } catch (JSONException e) {
                Log.i("TAG", "Error : " + e.getLocalizedMessage());
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            if (progressDialog != null)
                progressDialog.dismiss();

            if (aBoolean){
                Toast.makeText(getApplicationContext(), "파일 업로드 성공", Toast.LENGTH_LONG).show();
            }  else{
                Toast.makeText(getApplicationContext(), "파일 업로드 실패", Toast.LENGTH_LONG).show();
            }

            // 임시 파일 삭제 (카메라로 사진 촬영한 이미지)
            if(mImageCaptureUri != null){
                File file = new File(mImageCaptureUri.getPath());
                if(file.exists()) {
                    file.delete();
                }
                mImageCaptureUri = null;
            }

            if (aBoolean){
                imagePath = null;
            }
            
        }

    }

    @Override
    public void onBackPressed() {
        backPressHandler.onBackPressed();
    }

    public boolean checkPermissions() {
        int result;
        List<String> permissionList = new ArrayList<>();
        for (String pm : permissions) {
            result = ContextCompat.checkSelfPermission(this, pm);
            if (result != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(pm);
            }
        }
        if (!permissionList.isEmpty()) {
            ActivityCompat.requestPermissions(this, permissionList.toArray(new String[permissionList.size()]), MULTIPLE_PERMISSIONS);
            return false;
        }
        return true;
    }

    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MULTIPLE_PERMISSIONS: {
                if (grantResults.length > 0) {
                    for (int i = 0; i < permissions.length; i++) {
                        if (permissions[i].equals(this.permissions[i])) {
                            if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                                showToast_PermissionDeny();
                            }
                        }
                    }
                } else {
                    showToast_PermissionDeny();
                }
                return;
            }
        }
    }

    public void showToast_PermissionDeny() {
        Toast.makeText(this, "권한 요청에 동의 해주셔야 이용 가능합니다. 설정에서 권한 허용 하시기 바랍니다.", Toast.LENGTH_SHORT).show();
        finish();
    }
}


앱 build.Gradle 설정 내용

apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "25.0.3"

    defaultConfig {
        applicationId "com.tistory.link2me.photoupload"
        minSdkVersion 19
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:22.0.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.squareup.okhttp3:okhttp:3.9.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.google.firebase:firebase-messaging:10.2.6'
    testCompile 'junit:junit:4.12'
}


public class NetworkHelper {

    /** CHECK WHETHER INTERNET CONNECTION IS AVAILABLE OR NOT */
    public static boolean checkConnection(Context context) {
        return  ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null;
    }
}

 public class OKHttpComm {
    //GET network request
    //@RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static String GET(String url) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();

        Response response = null;
        try {
            response = client.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            Log.e("OKHttp", "error in getting response get request okhttp");
        }
        return null;
    }

    //POST network request
    public static String POST(String url, RequestBody body) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }   
}

 public class PHPComm extends Activity {

    // serverURL : JSON 요청을 받는 서버의 URL
    // postParams : POST 방식으로 전달될 입력 데이터
    // 반환 데이터 : 서버에서 전달된 JSON 데이터
    public static String getJson(String serverUrl, String postParams) throws Exception {

        BufferedReader bufferedReader = null;  
        try {  
            //Thread.sleep(100);
            URL url = new URL(serverUrl);  
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 세션 쿠키 전달
            String cookieString = CookieManager.getInstance().getCookie(Value.IPADDRESS);
            
            StringBuilder sb = new StringBuilder();  

            if(conn != null){ // 연결되었으면
                //add request header
                conn.setRequestMethod("POST");
                conn.setRequestProperty("USER-AGENT", "Mozilla/5.0");
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
                if (cookieString != null) {
                   conn.setRequestProperty("Cookie", cookieString);
                   Log.e("PHP_getCookie", cookieString);
                 }
                conn.setConnectTimeout(10000);
                conn.setReadTimeout(10000);
                conn.setUseCaches(false);
                conn.setDefaultUseCaches(false);
                conn.setDoOutput(true); // POST 로 데이터를 넘겨주겠다는 옵션
                conn.setDoInput(true);

                // Send post request
                DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
                wr.writeBytes(postParams);
                wr.flush();
                wr.close();

                int responseCode = conn.getResponseCode();
                System.out.println("GET Response Code : " + responseCode);        
                if(responseCode == HttpURLConnection.HTTP_OK){ // 연결 코드가 리턴되면
                    bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    String json;
                    while((json = bufferedReader.readLine())!= null){
                        sb.append(json + "\n");
                    }      
                }
                bufferedReader.close();
            }
            System.out.println("PHP Comm Out Size : " + sb.length());
            return sb.toString().trim();  
            // 수행이 끝나고 리턴하는 값은 다음에 수행될 onProgressUpdate 의 파라미터가 된다
        } catch(Exception e){  
            return new String("Exception: " + e.getMessage());
        }   
 
    }

}



2017.9.20 수정 사항

안드로이드 7.0 (삼성 갤럭시 기준)에서 이미지 저장하는 것이 기존 것과 달라서 다른 방법으로 시도를 해봤지만 compileSdkVersion 22 로 해서인지 다른 블로그에서 해보라는 방식으로 해도 안된다.

수정 테스트한 것만 발췌하여 적어둔다.




2017.9.21 LG LGM-X600K 테스트

LG폰을 구해서 사진 촬영 및 이미지 업로드 테스트를 했더니 기존 소스 코드로 해야만 동작이 되더라.

그래서 아래 부분을 보완했다.

대부분 KIKAT 이상 단말이므로 sendBroadcast(new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(mediaFile)) ); 부분만 코드에 추가해도 될 것으로 본다.


case CROP_FROM_CAMERA:  {
    // CROP 된 이후의 이미지를 넘겨 받음
    final Bundle extras = data.getExtras();

    // CROP 된 이미지를 저장하기 위한 File 경로 설정
    String filePath = getFileUri(saveFileName).getPath();
    imagePath = filePath;

    if(extras != null) {
        //photoBitmap = extras.getParcelable("data"); // CROP된 BITMAP
        photoBitmap = (Bitmap)data.getExtras().get("data"); // CROP된 BITMAP
        saveCropImage(photoBitmap,filePath); //  CROP 된 이미지를 외부저장소, 앨범에 저장한다.
        // sendBroadcast를 통해 Crop된 사진을 앨범에 보이도록 갱신한다.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            sendBroadcast(new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(mediaFile)) );
        } else {
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
        }
    }

    photoBitmap = BitmapFactory.decodeFile(imagePath );
    // 레이아웃의 이미지칸에 CROP된 BITMAP을 보여줌
    imageView.setImageBitmap(photoBitmap);

    break;
}


블로그 이미지

Link2Me

,