无法让HttpClient执行Imgur API v3发布请求

时间:2013-03-14 04:22:10

标签: java android api upload imgur

我正在尝试构建一个匿名上传到Imgur API v3的应用,这似乎会导致NullPointerException。我确实已将Internet权限添加到我的清单中,因此我不确定为什么这不起作用。 client-id被删除的原因很明显。任何建议都将不胜感激。

public HttpResponse uploadImage(String image_contents) {
    /* defining imgur api location */
    String API = ("https://api.imgur.com/3/image.json");
    Uri imgurAPI = (Uri.parse(API));

    // url encoding for bitmap

    // String dev_key = ("anon-dev-key-removed");
    String client_id = ("client-id-removed");
    /* String client_secret = ("secret-id-removed"); */
    /* constructing query */
    // spawning apache httpclient and post instance
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(API);
    // defining namevaluepairs for post data and setting entity
    // httpclient help from this url:
    // http://www.vogella.com/articles/ApacheHttpClient/article.html
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    nameValuePairs.add(new BasicNameValuePair("image", image_contents));
    /* for debugging purposes */
    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
    /* end for debugging purposes */
    try {
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    // adding oauth2 header with clientid
    httppost.addHeader("Authorization", "Client-ID " + client_id);
    // execute the post and collect the response as a httpresponse object

    HttpResponse response = null;
    changeText(httppost.toString());
    try {
        response = httpclient.execute(httppost);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    /* shut down http client */
    httpclient.getConnectionManager().shutdown();

    return response;
}

uploadImage()不会崩溃,但当我尝试处理HttpResponse时,我会得到NullPointerException

public void provideURL(HttpResponse response) {
    int responseCode=response.getStatusLine().getStatusCode();
    changeText("test");
}

1 个答案:

答案 0 :(得分:1)

最近可能已经改变了...但是使用带有imgur 3.0 API的Apache HTTP客户端(至少在我编写代码时)。您必须为HTTP客户端添加一些特殊的SSL处理代码。如果不这样做,您的请求将失败:

 // io exception with the message: (hostname in certificate didn't match: <api.imgur.com>    != <imgur.com> OR <imgur.com>)

你可以看到你到底需要做什么(我向其他人解释了这个问题): https://groups.google.com/forum/#!topic/imgur/RQytzya5aa4

在发出请求时(在catch块中),您是否看到任何异常?如果没有,可能SSL配置不再是问题。