匿名上传File对象到Imgur API(JSON)给出了身份验证错误401

时间:2013-05-19 20:58:45

标签: java android json api imgur

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

以下是我从Imgur收到的JSON的截图:

Imgur Screenshot

我在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)。

没有合法的方法将链接(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);
}

导致问题的原因是什么?

1 个答案:

答案 0 :(得分:10)

从api.imgur.com文档中,重点是我的:

  

API要求每个客户端使用OAuth 2身份验证。这意味着   您必须注册您的应用程序,并生成access_code   如果您想以用户身份登录。

     

对于公共只读和匿名资源,例如获取图片信息,查找用户评论等,您只需发送一个   您的请求中包含client_id的授权标头。这也是   如果你想匿名上传图像(没有图像),则可以正常工作   被绑在帐户上),或者如果你想创建一个匿名者   专辑。这让我们知道哪个应用程序正在访问API。

     

授权:客户ID-YOUR_CLIENT_ID

很明显,您需要为请求添加授权标头才能使其正常工作。使用Apache HttpClient就像这样简单:

httpPost.setHeader("Authorization", yourClientId);