我尝试使用apache commons库从我的Android应用程序发送帖子请求,但遇到了一些问题,可能是由于我对ASyncTasks缺乏了解
这是我写的相关代码
private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
@Override
protected Double doInBackground(String... params) {
postData(params[0]);
return null;
}
};
public void postData(String name) {
//showMessage("Transaction timed out");
HttpClient httpClient = new DefaultHttpClient();
// replace with your url
HttpPost httpPost = new HttpPost("http://posttestserver.com/post.php");
//Post Data
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("username", name));
nameValuePair.add(new BasicNameValuePair("password", "123456789"));
//Encoding POST data
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// log exception
e.printStackTrace();
}
//making POST request.
try {
HttpResponse response = httpClient.execute(httpPost);
// write response to log
Log.d("Http Post Response:", response.toString());
} catch (ClientProtocolException e) {
// Log exception
e.printStackTrace();
} catch (IOException e) {
// Log exception
e.printStackTrace();
}
}
public void postClick(View v)
{
new MyAsyncTask().doInBackground("JACK");
}
如果有必要,可以发布堆栈跟踪,但我可能只是做了一些愚蠢的错误,但我无法弄清楚为什么
答案 0 :(得分:0)
直接来自:docs
AsyncTask的泛型类型:
异步任务使用的三种类型如下:
并非所有类型都始终由异步任务使用。要将类型标记为未使用,只需使用类型Void:
private class MyTask extends AsyncTask<Void, Void, Void> { ... }
用法示例:
imageView = (ImageView) findViewById(R.id.image_view);
//This task is going to execute "downloadFile(imageHttpAddress)"
// and so it defines String as its param type - this will be sent to doInBackground(),
// it will not post any progress and so Void for progress and finally, Bitmap as its answer
new AsyncTask<String, Void, Bitmap>(){
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Bitmap doInBackground(String... url) {
return downloadFile(url[0]);
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
imageView.setImageBitmap(bitmap);
}
}.execute(imageHttpAddress);
//This method takes a string (url to some image) and returns a bitmap
private Bitmap downloadFile(String imageHttpAddress) {
URL imageUrl = null;
try {
imageUrl = new URL(imageHttpAddress);
HttpURLConnection conn =(HttpURLConnection)imageUrl.openConnection();
conn.connect();
loadedImage = BitmapFactory.decodeStream(conn.getInputStream());
return loadedImage;
} catch (IOException e) {
e.printStackTrace();
}
}
希望这有帮助。
答案 1 :(得分:0)
来自文件: AsyncTask 是Android提供的一个抽象类,它可以帮助我们正确使用UI线程。该类允许我们执行长/后台操作并在UI线程上显示其结果,而无需操纵线程。 AsyncTask有四个步骤:
doInBackground :此方法执行长时间运行的代码。当单击按钮执行onClick方法时,它调用execute方法接受参数并自动调用doInBackground方法并传递参数。
onPostExecute :在doInBackground方法完成处理后调用此方法。来自doInBackground的结果将传递给此方法。
onPreExecute :在调用doInBackground方法之前调用此方法。
onProgressUpdate :通过从doInBackground调用此方法随时调用publish-progress来调用此方法。
public class Restcaliing extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
try {
ServiceHandler serviceHandler = new ServiceHandler();
reststring = serviceHandler.makeServiceCall(prepaerdurl, ServiceHandler.POST);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), "" + reststring, Toast.LENGTH_SHORT).show();
}
}
这是我的ServiceHandler类。
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Making service call
*
* @url - url to make request
* @method - http request method
*/
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
*
* @url - url to make request
* @method - http request method
* @params - http request params
*/
public String makeServiceCall(String url, int method, List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
Log.d("serv handler response"," "+response);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
new Restcaliing().execute();
这就是我如何调用AsyncTask。
希望你能理解并帮助你。