1

我正在通过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;
    }
}

}

4

2 回答 2

1

尝试这个..

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

}.start();
于 2012-04-13T09:16:11.210 回答
0

我整理了一个android的异步http操作库,看看能不能帮到你。您可以从活动或 IntentService 进行异步 http 调用

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

于 2012-04-13T09:59:19.640 回答