小编Awa*_*ran的帖子

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

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

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

Imgur截图

我在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 …
Run Code Online (Sandbox Code Playgroud)

java api android json imgur

4
推荐指数
1
解决办法
5551
查看次数

onPostExecute不允许我创建Toast消息

请在上面看到这个上下文:匿名上传文件对象到Imgur API(JSON)给出了身份验证错误401(如果有人感兴趣,它有doInBackground()方法的代码)

使用AsyncTask类,我将图像上传到Imgur.上传过程在doInBackground()方法中完成.它返回指向onPostExecute的String链接,该链接应以Toast消息的形式显示链接.

@Override
protected void onPostExecute(String result) 
{
    super.onPostExecute(result);
    Toast.makeText(getApplicationContext(), "Uploaded! Link: " + result, Toast.LENGTH_SHORT).show();
}
Run Code Online (Sandbox Code Playgroud)

但是,这样做会产生以下错误:

对于UploadToImgurTask类型,方法getApplicationContext()未定义

尝试将返回字符串复制到剪贴板会产生类似的问题.

@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)

对于UploadToImgurTask类型,方法getSystemService(String)未定义

java clipboard android imgur android-asynctask

2
推荐指数
1
解决办法
3877
查看次数

标签 统计

android ×2

imgur ×2

java ×2

android-asynctask ×1

api ×1

clipboard ×1

json ×1