gpt4 book ai didi

java - 匿名上传文件对象到 Imgur API (JSON) 给出身份验证错误 401

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:54:08 29 4
gpt4 key购买 nike

我创建了一个类 UploadToImgurTask 作为 AsyncTask,它采用单个文件路径参数,创建并设置一个 MultiPartEntity,然后使用 Apache HttpClient 上传带有所述实体的图像。来自 Imgur 的 JSON 响应保存在一个 JSONObject 中,我将其内容显示在 LogCat 中以供我自己理解。

这是我从 Imgur 收到的 JSON 的屏幕截图:

Imgur Screenshot

我在 api.imgur.com 上查找了错误 Status 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);
}

是什么导致了这个问题?

最佳答案

来自 api.imgur.com 文档,重点是我的:

The API requires each client to use OAuth 2 authentication. This means you'll have to register your application, and generate an access_code if you'd like to log in as a user.

For public read-only and anonymous resources, such as getting image info, looking up user comments, etc. all you need to do is send an authorization header with your client_id in your requests. This also works if you'd like to upload images anonymously (without the image being tied to an account), or if you'd like to create an anonymous album. This lets us know which application is accessing the API.

Authorization: Client-ID YOUR_CLIENT_ID

很明显,您需要向请求添加授权 header 才能使其正常工作。使用 Apache HttpClient 就这么简单:

httpPost.setHeader("Authorization", yourClientId);

关于java - 匿名上传文件对象到 Imgur API (JSON) 给出身份验证错误 401,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16639425/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com