2013-03-14 66 views
2

我正尝试构建一个匿名上传到Imgur API v3的应用程序,并且这似乎会导致NullPointerException。我确实已将互联网许可添加到我的清单,因此我不确定为何这不起作用。由于显而易见的原因,client-id被删除。任何建议将不胜感激。无法让HttpClient执行Imgur API v3发布请求

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"); 
} 
+0

你需要做一个HTTPS请求,而不是HTTP bez你的webservice url包含HTTPS协议而不是HTTP – 2013-03-14 04:29:04

+0

@ρяσѕρєяK我可能是错的,但我认为只要你提供了正确的URL,HttpClient就可以使用HTTPS。我刚刚通过切换到Imgur API v2来工作,但我不确定为什么这不适用于版本3。 – digitalsteez 2013-03-14 06:05:34

回答

1

它最近可能有所变化......但与imgur使用Apache HTTP客户端3.0 API(至少当我为它编码时)。您将不得不为您的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配置不再是问题。