728x90

제목 : 개도국 배려한 페북 안드로이드 앱 업뎃 화제
관련기사 : http://www.zdnet.co.kr/news/news_view.asp?artice_id=20140620103700&type=det&re=

OkHttp는 안드로이드 및 자바 애플리케이션용 HTTP 및 SPDY 프로토콜 클라이언트다.
HTTP 프로토콜의 효율성을 높여주고 전체 네트워킹 속도를 향상시키면서 대역폭을 절감시켜준다.
스퀘어에서 만든 이 오픈소스 클라이언트는 전격적으로 페이스북 안드로이드앱에 채택됐다.
OkHttp로 교체하자 뉴스피드의 이미지 로드 실패가 줄어들었다.


안드로이드 스튜디오 기반 OKHttp 라이브러리를 이용하여 갤러리에서 이미지를 선택하여 서버(PHP)에 업로드하는 괜찮은 소스를 찾았다.


https://github.com/pratikbutani/OKHTTPUploadImage 에서 파일을 다운로드 받아서 Import 하면 예제를 실행해 볼 수 있다.


나중에 다른 소스에 활용하기 위해 내가 사용하는 코드 명칭으로 일부 수정했고, 해당 메소드에 대한 설명을 추가해서 테스트 했다.


gradle 추가

    compile 'com.squareup.okhttp3:okhttp:3.8.1'
    compile 'com.squareup.picasso:picasso:2.5.2'

서버에 업로드하려면 인터넷 연결이 되어야 하고 갤러리에 접속하려면 권한이 부여되어야 한다.

 <uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>


// 선택된 사진을 받아 서버에 업로드한다.
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (!TextUtils.isEmpty(imagePath)) {
            if (NetworkHelper.checkConnection(mContext)) { // 인터넷 연결 체크
                String ImageUploadURL = "http://192.168.0.100/upload/upload.php";
                new ImageUploadTask().execute(ImageUploadURL, imagePath);
            } else {
                Toast.makeText(mContext, "인터넷 연결을 확인하세요", Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(mContext, "먼저 업로드할 파일을 선택하세요", Toast.LENGTH_SHORT).show();
        }
    }
});

private  class ImageUploadTask extends AsyncTask<String, Integer, Boolean> {
    ProgressDialog progressDialog;

    @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]);
            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();

        imagePath = "";
        textView.setVisibility(View.VISIBLE);
        imageView.setVisibility(View.INVISIBLE);
    }
}

// 사진 선택을 위해 갤러리를 호출
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, getString(R.string.string_choose_image));
    startActivityForResult(chooserIntent, 1010);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // URI 정보를 이용하여 사진 정보를 가져온다.
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK && requestCode == 1010) {
        if (data == null) {
            Snackbar.make(findViewById(R.id.parentView), "Unable to Pickup Image", Snackbar.LENGTH_INDEFINITE).show();
            return;
        }
        Uri selectedImageUri = data.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};

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

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

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            imagePath = cursor.getString(columnIndex);

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

        } else {
            Snackbar.make(findViewById(R.id.parentView), "Unable to Load Image", Snackbar.LENGTH_LONG).setAction("Try Again", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getGallery();
                }
            }).show();
        }

        textView.setVisibility(View.GONE);
        imageView.setVisibility(View.VISIBLE);
    }
}



public class JSONParser {

    public static JSONObject uploadImage(String imageUploadUrl, String sourceImageFile) {

        try {
            File sourceFile = new File(sourceImageFile);
            Log.d("TAG", "File...::::" + sourceFile + " : " + sourceFile.exists());
            final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/*");
            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("result", "photo_image")
                    .build();

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

            OkHttpClient client = new OkHttpClient();
            Response response = client.newCall(request).execute();
            String res = response.body().string();
            Log.e("TAG", "Error: " + 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;
    }
}


MediaType.parse("image/*")  // add ImageFile
MediaType.parse("image/jpeg") // add JPEG ImageFile
MediaType.parse("text/plain") // add TextFile
MediaType.parse("application/zip")  // add ZipFile
MediaType.parse("application/json; charset=utf-8")


PHP 파일

<?php
    $file_path = "";
    $file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
        // 동일한 파일명이면 덮어쓰기를 한다.
        $result = array("result" => "success");
    } else{
        $result = array("result" => "error");
    }
    echo json_encode($result);
?>



=== OKHttp 라이브러리를 이용한 파일 전송 핵심코드 ===

final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/*");
String filename = ImagePath.substring(ImagePath.lastIndexOf("/") + 1);

RequestBody requestBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("image", filename, RequestBody.create(MEDIA_TYPE_PNG, sourceFile))
        .addFormDataPart("result", "my_image")
        .addFormDataPart("username", name)
        .addFormDataPart("password", password)
        .addFormDataPart("email", email)
        .addFormDataPart("phone", phone)
        .build();

Request request = new Request.Builder()
        .url(BASE_URL + "signup")
        .post(requestBody)
        .build();

OkHttpClient client = new OkHttpClient();
okhttp3.Response response = client.newCall(request).execute();
res = response.body().string();

블로그 이미지

Link2Me

,