我创建了一个类UploadToImgurTask
作为 AsyncTask,它采用单个文件路径参数,创建并设置 MultiPartEntity,然后使用 Apache HttpClient 上传带有所述实体的图像。来自 Imgur 的 JSON 响应保存在 JSONObject 中,我将其内容显示在 LogCat 中以供我自己理解。
这是我从 Imgur 收到的 JSON 的屏幕截图:
我在 api.imgur.com 上查找错误状态 401,它说我需要使用 OAuth 进行身份验证,尽管Imgur 已经非常清楚地表明,如果图像是匿名上传的,应用程序不需要使用 OAuth(这就是我我现在正在做)。
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;
}
}
在 doInBackground 将上传图像的链接返回到 onPostExecute 后,我想将其复制到系统剪贴板,但 Eclipse 一直说 getSystemService(String) 未在我的 ASyncTask 类中定义。
没有合法的方法可以将链接(字符串)返回到主线程,所以我必须在 UploadToImgurTask(扩展 ASyncTask)中的 onPostExecute 中做任何我必须做的事情
@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);
}
是什么导致了问题?