Awa*_*ran 4 java api android json imgur
我创建了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;
}
}
Run Code Online (Sandbox Code Playgroud)
在doInBackground将上传图像的链接返回到onPostExecute后,我想将其复制到系统剪贴板,但Eclipse一直说我的ASyncTask类中没有定义getSystemService(String).
没有合法的方法将链接(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);
}
Run Code Online (Sandbox Code Playgroud)
是什么导致了这个问题?
Per*_*ion 10
从api.imgur.com文档中,重点是我的:
API要求每个客户端使用OAuth 2身份验证.这意味着您必须注册您的应用程序,并在您想以用户身份登录时生成access_code.
对于公共只读和匿名资源,例如获取图像信息,查找用户评论等,您只需在请求中发送带有client_id的授权标头.如果您想要匿名上传图像(图像不附加到帐户),或者您想要创建匿名相册,这也适用.这让我们知道哪个应用程序正在访问API.
授权:Client-ID YOUR_CLIENT_ID
很明显,您需要为请求添加授权标头才能使其正常工作.使用Apache HttpClient就像这样简单:
httpPost.setHeader("Authorization", yourClientId);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5551 次 |
最近记录: |