我正在尝试构建一个匿名上传到 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");
}