use*_*582 8 post android http android-asynctask
请问任何人都可以告诉我如何使用AsyncTask在后台使用http帖子以及如何将参数传递给AsyncTask?我发现的所有示例对我来说都不够清楚,而且它们是关于下载文件的.
我在我的主要活动中运行此代码,我的问题是当代码将信息发送到服务器时,应用程序速度减慢,好像它被冻结了2到3秒,然后它继续正常工作,直到下一次发送.此http帖子向服务器发送四个变量(book,libadd和time),第四个是固定的(名称)
提前致谢
public void SticketFunction(double book, double libadd, long time){
Log.v("log_tag", "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SticketFunction()");
//HttpClient
HttpClient nnSticket = new DefaultHttpClient();
//Response handler
ResponseHandler<String> res = new BasicResponseHandler();
HttpPost postMethod = new HttpPost("http://www.books-something.com");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("book", book+""));
nameValuePairs.add(new BasicNameValuePair("libAss", libass+""));
nameValuePairs.add(new BasicNameValuePair("Time", time+""));
nameValuePairs.add(new BasicNameValuePair("name", "jack"));
//Encode and set entity
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
//Execute
//manSticket.execute(postMethod);
String response =Sticket.execute(postMethod, res).replaceAll("<(.|\n)*?>","");
if (response.equals("Done")){
//Log.v("log_tag", "!!!!!!!!!!!!!!!!!! SticketFunction got a DONE!");
}
else Log.v("log_tag", "!!!!!!!?????????? SticketFunction Bad or no response: " + response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
//Log.v("log_tag", "???????????????????? SticketFunction Client Exception");
} catch (IOException e) {
// TODO Auto-generated catch block
//Log.v("log_tag", "???????????????????? IO Exception");
}
}
}
Run Code Online (Sandbox Code Playgroud)
Mit*_*oto 29
首先,你把一个类如下:
public class AsyncHttpPost extends AsyncTask<String, String, String> {
interface Listener {
void onResult(String result);
}
private Listener mListener;
private HashMap<String, String> mData = null;// post data
/**
* constructor
*/
public AsyncHttpPost(HashMap<String, String> data) {
mData = data;
}
public void setListener(Listener listener) {
mListener = listener;
}
/**
* background
*/
@Override
protected String doInBackground(String... params) {
byte[] result = null;
String str = "";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(params[0]);// in this case, params[0] is URL
try {
// set up post data
ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
Iterator<String> it = mData.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
nameValuePair.add(new BasicNameValuePair(key, mData.get(key)));
}
post.setEntity(new UrlEncodedFormEntity(nameValuePair, "UTF-8"));
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK){
result = EntityUtils.toByteArray(response.getEntity());
str = new String(result, "UTF-8");
}
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (Exception e) {
}
return str;
}
/**
* on getting result
*/
@Override
protected void onPostExecute(String result) {
// something...
if (mListener != null) {
mListener.onResult(result)
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在.你只需写下如下几行:
HashMap<String, String> data = new HashMap<String, String>();
data.put("key1", "value1");
data.put("key2", "value2");
AsyncHttpPost asyncHttpPost = new AsyncHttpPost(data);
asyncHttpPost.setListener(new AsyncHttpPost.Listener(){
@Override
public void onResult(String result) {
// do something, using return value from network
}
});
asyncHttpPost.execute("http://example.com");
Run Code Online (Sandbox Code Playgroud)
首先,我不建议在 AsyncTask 中执行 Http 请求,您最好尝试使用 Service。回到关于如何在声明 AsyncTask 时将参数传递到 AsyncTask 的问题,您可以像这样定义AsyncTask的每个对象类。
public AsyncTask <Params,Progress,Result> {
}
Run Code Online (Sandbox Code Playgroud)
所以在你的任务中你应该这样
public MyTask extends<String,Void,Void>{
public Void doInBackground(String... params){//those Params are String because it's declared like that
}
}
Run Code Online (Sandbox Code Playgroud)
使用起来非常简单
new MyTask().execute("param1","param2","param3")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26208 次 |
| 最近记录: |