I've created a class UploadToImgurTask
as an AsyncTask that takes a single file path parameter, creates and sets an MultiPartEntity, and then uses Apache HttpClient to upload the image with said entity. The JSON response from Imgur is saved in a JSONObject, the contents of which I display in LogCat for my own understanding.
Here's a screenshot of the JSON I receive from Imgur:
I looked up error Status 401 on api.imgur.com and it says that I need to authenticate using OAuth despite the fact that Imgur has stated very clearly that apps do not need to use OAuth if images are being uploaded anonymously (which is what I am doing right now).
class UploadToImgurTask extends AsyncTask<String, Void, Boolean> {
String upload_to;
@Override
protected Boolean doInBackground(String... params) {
final String upload_to = "https://api.imgur.com/3/upload.json";
final String API_key = "API_KEY";
final String TAG = "Awais";
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(upload_to);
try {
final MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("image", new FileBody(new File(params[0])));
entity.addPart("key", new StringBody(API_key));
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("JSON", json.toString()); //for my own understanding
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
After doInBackground returns the link to the uploaded image to onPostExecute, I want to copy it to the system clipboard, but Eclipse keeps saying getSystemService(String) isn't defined within my ASyncTask class.
There is no legit way to return link (a String) back to the main thread, so I have to do whatever I have to do within onPostExecute within UploadToImgurTask (which extends ASyncTask)
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label", "Text to copy");
clipboard.setPrimaryClip(clip);
}
What's causing the problem?