2013-03-14 39 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配置不再是問題。