Welcome to FutureAppLaboratory

v=(*^ワ^*)=v

Upload Pics by Imgur Api on Android

| Comments

Introduction

This an example android application which use Imgur’s api to upload image, with OAuth2 authorization.

Steps

  1. You need an account on Imgur. Then create an app from “Settings -> Applications”. The redirect link should set to YOUR_APP_IDENTIFIER://callback or something else you like, but must match scheme in step 5.
  2. Get your app’s client id.
  3. Replace it with CLIENT_ID in the source code.
  4. Create an sample android project with an activity with the source code below.
  5. Add following lines to AndroidManifest.xml, under Activity OAuthTestActivity. This allows transition from authorization page to your android app.

     <intent-filter>
         <action android:name="android.intent.action.VIEW" />
         <category android:name="android.intent.category.DEFAULT" />
         <category android:name="android.intent.category.BROWSABLE" />
         <data android:scheme="YOUR_APP_IDENTIFIER" android:host="callback" />
     </intent-filter>
    
  6. Build and Run.

  7. Authorize with your imgur’s account with your web browser. Image A
  8. Choose an image to upload. Image B
  9. Upload. Image C
  10. Check the uploaded image in your web browser. Image D

Source Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
public class OAuthTestActivity extends Activity {

    public static final int REQUEST_CODE_PICK_IMAGE = 1001;

    private static final String AUTHORIZATION_URL = "https://api.imgur.com/oauth2/authorize";
    private static final String CLIENT_ID = "CLIENT_ID";

    private LinearLayout rootView;

    private String accessToken;
    private String refreshToken;

    private String picturePath = "";
    private Button send;

    private String uploadedImageUrl = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        rootView = new LinearLayout(this);
        rootView.setOrientation(LinearLayout.VERTICAL);
        TextView tv = new TextView(this);
        LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        tv.setLayoutParams(llp);
        rootView.addView(tv);
        setContentView(rootView);

        String action = getIntent().getAction();

        if (action == null || !action.equals(Intent.ACTION_VIEW)) { // We need access token to use Imgur's api

            tv.setText("Start OAuth Authorization");

            Uri uri = Uri.parse(AUTHORIZATION_URL).buildUpon()
                    .appendQueryParameter("client_id", CLIENT_ID)
                    .appendQueryParameter("response_type", "token")
                    .appendQueryParameter("state", "init")
                    .build();

            Intent intent = new Intent();
            intent.setData(uri);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();

        } else { // Now we have the token, can do the upload

            tv.setText("Got Access Token");

            Uri uri = getIntent().getData();
            Log.d("Got imgur's access token", uri.toString());
            String uriString = uri.toString();
            String paramsString = "http://callback?" + uriString.substring(uriString.indexOf("#") + 1);
            Log.d("tag", paramsString);
            List<NameValuePair> params = URLEncodedUtils.parse(URI.create(paramsString), "utf-8");
            Log.d("tag", Arrays.toString(params.toArray(new NameValuePair[0])));

            for (NameValuePair pair : params) {
                if (pair.getName().equals("access_token")) {
                    accessToken = pair.getValue();
                } else if (pair.getName().equals("refresh_token")) {
                    refreshToken = pair.getValue();
                }
            }

            Log.d("tag", "access_token = " + accessToken);
            Log.d("tag", "refresh_token = " + refreshToken);

            Button chooseImage = new Button(this);
            rootView.addView(chooseImage);
            chooseImage.setText("Choose an image");
            chooseImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
                }
            });

            send = new Button(this);
            rootView.addView(send);
            send.setText("send to imgur");
            send.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (picturePath != null && picturePath.length() > 0 &&
                            accessToken != null && accessToken.length() > 0) {
                        (new UploadToImgurTask()).execute(picturePath);
                    }
                }
            });
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (send == null) return;
        if (picturePath == null || picturePath.length() == 0) {
            send.setVisibility(View.GONE);
        } else {
            send.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("tag", "request code : " + requestCode + ", result code : " + resultCode);
        if (data == null) {
            Log.d("tag" , "data is null");
        }
        if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_PICK_IMAGE && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

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

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            picturePath = cursor.getString(columnIndex);
            Log.d("tag", "image path : " + picturePath);
            cursor.close();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    // Here is the upload task
    class UploadToImgurTask extends AsyncTask<String, Void, Boolean> {

        @Override
        protected Boolean doInBackground(String... params) {
            final String upload_to = "https://api.imgur.com/3/upload";

            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost(upload_to);

            try {
                HttpEntity entity = MultipartEntityBuilder.create()
                        .addPart("image", new FileBody(new File(params[0])))
                        .build();

                httpPost.setHeader("Authorization", "Bearer " + accessToken);
                httpPost.setEntity(entity);

                final HttpResponse response = httpClient.execute(httpPost,
                        localContext);

                final String response_string = EntityUtils.toString(response
                        .getEntity());

                final JSONObject json = new JSONObject(response_string);

                Log.d("tag", json.toString());

                JSONObject data = json.optJSONObject("data");
                uploadedImageUrl = data.optString("link");
                Log.d("tag", "uploaded image url : " + uploadedImageUrl);

                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            if (aBoolean.booleanValue()) { // after sucessful uploading, show the image in web browser
                Button openBrowser = new Button(OAuthTestActivity.this);
                rootView.addView(openBrowser);
                openBrowser.setText("Open Browser");
                openBrowser.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent();
                        intent.setData(Uri.parse(uploadedImageUrl));
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }
                });
            }
        }
    }

}

Comments