在不等待响应的情况下将Usage日志发送到服务器的最佳方法是什么

时间:2012-04-13 09:14:17

标签: android http

我正在通过http post发送一个使用日志,例如按钮点击或页面导航到我的服务器,现在我正在使用asynctask doInBackground,但是我的doInBackground方法将在服务器响应之前完成。

问题是:发送http帖子并忽略来自服务器的响应是否更好。但我需要确保服务器记录日志。

private static class Async extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        String url = "server url";
        DefaultHttpClient httpclient = new DefaultHttpClient();
        httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("username", "password"));
        HttpPost httppost = new HttpPost(url);
        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("DeviceOS", "Android"));
            nameValuePairs.add(new BasicNameValuePair("OSVersion", osVersion));
            nameValuePairs.add(new BasicNameValuePair("DeviceManufacturer", manufacturer));
            nameValuePairs.add(new BasicNameValuePair("Model", model));
            // and some more
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String responseBody = httpclient.execute(httppost, responseHandler);

        } catch (ClientProtocolException e) {
            // Error msg will be here = e.getMessage();
        } catch (IOException e) {
            // Error msg will be here = e.getMessage();
        }
        return null;
    }
}

}

2 个答案:

答案 0 :(得分:1)

试试这个..

Thread r = new Thread(){
public void run(){
  //post request
}

}.start();

答案 1 :(得分:0)

我已经为android设置了异步http操作库,请看看它是否可以帮到你。您可以从活动或IntentService

进行asyn http调用

https://github.com/nareshsvs/android-libraries