Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/apache/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
android http post异步任务_Android_Http_Post_Android Asynctask - Fatal编程技术网

android http post异步任务

android http post异步任务,android,http,post,android-asynctask,Android,Http,Post,Android Asynctask,请告诉我如何使用AsyncTask使http post在后台工作,以及如何将参数传递给AsyncTask?我发现的所有示例对我来说都不够清楚,它们都是关于下载文件的 我在我的主要活动中运行这段代码,我的问题是,当代码将信息发送到服务器时,应用程序会减慢速度,好像它被冻结了2到3秒,然后继续正常工作,直到下一次发送。此http post向服务器发送四个变量(book、libadd和time),第四个变量是固定的(name) 提前谢谢 public void SticketFunction

请告诉我如何使用AsyncTask使http post在后台工作,以及如何将参数传递给AsyncTask?我发现的所有示例对我来说都不够清楚,它们都是关于下载文件的

我在我的主要活动中运行这段代码,我的问题是,当代码将信息发送到服务器时,应用程序会减慢速度,好像它被冻结了2到3秒,然后继续正常工作,直到下一次发送。此http post向服务器发送四个变量(book、libadd和time),第四个变量是固定的(name)

提前谢谢

    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");
        } 
    }

}
公共作废粘贴功能(双簿、双libadd、长时间){
Log.v(“日志标签”,“SticketFunction()”);
//HttpClient
HttpClient nnSticket=new DefaultHttpClient();
//响应处理程序
ResponseHandler res=新的BasicResponseHandler();
HttpPost postMethod=新的HttpPost(“http://www.books-something.com");
试一试{
List nameValuePairs=新的ArrayList(5);
添加(新的BasicNameValuePair(“book”,book+);
添加(新的BasicNameValuePair(“libAss”,libAss+);
添加(新的BasicNameValuePair(“时间”,时间+);
添加(新的BasicNameValuePair(“名称”、“杰克”));
//编码和设置实体
setEntity(新的UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
//执行
//manstick.execute(postMethod);
字符串响应=Sticket.execute(postMethod,res.replaceAll(“,”);
if(response.equals(“Done”)){
//Log.v(“Log_tag”,“!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!粘贴功能完成了!”);
}
else Log.v(“Log_tag”、“!!!!!?????????SticketFunction错误或无响应:“+响应”);
}catch(ClientProtocolException e){
//TODO自动生成的捕捉块
//Log.v(“Log_标记”,“SticketFunction客户端异常”);
}捕获(IOE){
//TODO自动生成的捕捉块
//Log.v(“日志标签”,“IO异常”);
} 
}
}

首先,我不建议在异步任务中执行Http请求,您最好尝试使用服务。回到如何在声明AsyncTask时将参数传递到AsyncTask的问题,您可以像这样定义每个对象类

public AsyncTask <Params,Progress,Result> {

}
起初,, 您放置了一个如下所示的类:

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)
        }
    }
}
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");
公共类AsyncHttpPost扩展了AsyncTask{
接口侦听器{
void onResult(字符串结果);
}
私人倾听者;
私有HashMap mData=null;//post数据
/**
*建造师
*/
公共异步HttpPost(哈希映射数据){
mData=数据;
}
公共void setListener(侦听器侦听器){
mListener=监听器;
}
/**
*背景
*/
@凌驾
受保护的字符串doInBackground(字符串…参数){
字节[]结果=空;
字符串str=“”;
HttpClient=new DefaultHttpClient();
HttpPost=newhttppost(参数[0]);//在本例中,参数[0]是URL
试一试{
//设置post数据
ArrayList nameValuePair=新的ArrayList();
迭代器it=mData.keySet().Iterator();
while(it.hasNext()){
String key=it.next();
添加(新的BasicNameValuePair(key,mData.get(key));
}
post.setEntity(新的UrlEncodedFormEntity(nameValuePair,“UTF-8”);
HttpResponse response=client.execute(post);
StatusLine StatusLine=response.getStatusLine();
if(statusLine.getStatusCode()==HttpURLConnection.HTTP\u OK){
结果=EntityUtils.toByteArray(response.getEntity());
str=新字符串(结果为“UTF-8”);
}
}
捕获(不支持的编码异常e){
e、 printStackTrace();
}
捕获(例外e){
}
返回str;
}
/**
*结果如何
*/
@凌驾
受保护的void onPostExecute(字符串结果){
//有些事。。。
if(mListener!=null){
mListener.onResult(result)
}
}
}
现在。 您只需写以下几行:

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)
        }
    }
}
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");
HashMap data=newhashmap();
数据输入(“键1”、“值1”);
数据。put(“键2”、“值2”);
AsyncHttpPost AsyncHttpPost=新的AsyncHttpPost(数据);
asyncHttpPost.setListener(新的asyncHttpPost.Listener(){
@凌驾
公共void onResult(字符串结果){
//使用来自网络的返回值做一些事情
}
});
asyncHttpPost.execute(“http://example.com");

什么是服务,您为什么建议这样做?关于Servicec有很多信息,主要区别在于服务没有附加到活动,在后台运行,但仍在主线程中,还有另一种称为IntentService的服务,它有一个在另一个线程中运行的方法。取决于我在执行Http请求时尝试使用服务的情况。好的,但为什么您更喜欢服务?是更安全、更快、更容易还是??主要原因之一是异步任务依赖于活动这意味着一旦活动完成,一个任务在没有上下文连接的情况下无法离开()该任务也将被删除,这意味着你的HttpCalled可能已经成功了,但你只是浪费了用户资源在一些你甚至不会使用的东西上;至于服务,您必须使用stopSelf或stopService显式地销毁它,或者从每个上下文中解除绑定,这样做更安全。要了解更多信息,请访问伟大的解决方案!将项目放入java文件中,然后开始。我见过的最轻松的异步发布方式。如何在类中访问AsyncHttpPost实例的结果?像charm thx一样工作,我一直在遵循不同的示例