android - 异步 HTTP post android

标签 android http-post

我正在使用一个应用程序,我只需要从 mysql 服务器下载一对谷歌地图的坐标。我可以使用 php 和普通的 httpost 成功地做到这一点,但是当我这样做时我的应用程序卡住了几秒钟。

我读到您需要使 httppost 异步,以避免在服务器完成处理并发送结果之前卡住。

关键是我需要像普通 httpost 一样生成一个 json 数组。

例如,如果我有这个 httppost。

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("id", "12345"));
    nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
} catch (IOException e) {
    // TODO Auto-generated catch block
}

String result11 = null;
// convert response to string
try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is11, "iso-8859-1"), 8);
    StringBuilder sb = new StringBuilder();
    sb.append(reader.readLine() + "\n");
    String line = "0";
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
    is11.close();
    result11 = sb.toString();
} catch (Exception e) {
    Log.e("log_tag", "Error converting result " + e.toString());
}

// parsing data
try {
    JSONArray jArray1 = new JSONArray(result11);
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

我怎样才能将其转换为异步发布,从而避免卡住?

最佳答案

有一个很好的类 AsyncTask 可以用来轻松地运行异步任务。如果您将代码嵌入到这样的子类中,您可能会得到这样的结果:

public class FetchTask extends AsyncTask<Void, Void, JSONArray> {
    @Override
    protected JSONArray doInBackground(Void... params) {
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("id", "12345"));
            nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

            BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            sb.append(reader.readLine() + "\n");
            String line = "0";
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            reader.close();
            String result11 = sb.toString();

            // parsing data
            return new JSONArray(result11);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    protected void onPostExecute(JSONArray result) {
        if (result != null) {
            // do something
        } else {
            // error occured
        }
    }
}

您可以使用以下方式开始任务:

new FetchTask().execute();

其他资源:

关于android - 异步 HTTP post android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9954477/

相关文章:

android - 适用于 Android 的 Tensorflow 示例

java - Spring POST multipart/form-data 请求正文为空,getParts 始终为空

android - 如何在 Android 中使用 HTTP POST 将图像作为 JSON 中的 base64 字符串发送?

Android - 使用 Httppost 将一些数据从 android 应用程序传递到 servlet,但它在 servlet 中变为空

php - 使用 Ajax post 查询多个表 (PHP-MYSQL)

java - 通过 Post Android 发送数据到 PHP

android - 将 Toast 消息转换为文本

java - 为什么我设置 this.getReadableDatabase() 后需要关闭数据库?

Android应用程序字体大小根据设置中定义的字体大小而变化

java - Android Studio - 单击按钮后当前 Activity 重新打开