AsyncTaskLoader
でHttpPost
リクエスト
こちらの記事を参考に作成したLoaderに、POST送信機能を実装してみた。
public class HttpAsyncLoader extends AsyncTaskLoader<String> {
private HttpUriRequest request = null;
public HttpAsyncLoader(Context context, String url) {
super(context);
this.request = new HttpGet(url);
}
public HttpAsyncLoader(Context context, String url, List<NameValuePair> postData) {
super(context);
HttpPost request = new HttpPost(url);
try {
request.setEntity(new UrlEncodedFormEntity(postData, "UTF-8"));
this.request = request;
} catch(UnsupportedEncodingException e) {
Log.e(this.getClass().getSimpleName(), e.getMessage());
}
}
@Override
public String loadInBackground() {
HttpClient httpClient = new DefaultHttpClient();
try {
String responseBody = httpClient.execute(request,
new ResponseHandler<String>() {
@Override
public String handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {
if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()) {
return EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
}
return null;
}
});
return responseBody;
}
catch(Exception e) {
Log.e(this.getClass().getSimpleName(), e.getMessage());
}
finally {
httpClient.getConnectionManager().shutdown();
}
return null;
}
}