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