【发布时间】:2013-05-14 09:57:55
【问题描述】:
我创建了一个类 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 一直说我的 ASyncTask 类中没有定义 getSystemService(String)。
没有合法的方式将链接(字符串)返回到主线程,所以我必须在 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);
}
导致问题的原因是什么?
【问题讨论】:
标签: java android json api imgur