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");
}
你需要做一個HTTPS請求,而不是HTTP bez你的webservice url包含HTTPS協議而不是HTTP – 2013-03-14 04:29:04
@ρяσѕρєяK我可能是錯的,但我認爲只要你提供了正確的URL,HttpClient就可以使用HTTPS。我剛剛通過切換到Imgur API v2來工作,但我不確定爲什麼這不適用於版本3。 – digitalsteez 2013-03-14 06:05:34