我正在使用一个应用程序,我只需要从mysql服务器下载一对谷歌地图的坐标。我可以成功地使用php和一个普通的httpost来做到这一点,但是当我这样做时,我的应用程序冻结了几秒钟。异步HTTP发布android
我读到,你需要使得httppost asycronous以避免冻结,直到服务器完成prossess并发送结果。
问题是,我需要像普通的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();
}
我如何可以转换到异步职位,所以我能避免冻结?
我不知道你的代码可以怎么连编译,因为它是,但请用['EntityUtils.toString(response.getEntity())'](http://stackoverflow.com/a/2324739/180740)而不是拥有自己的BufferedReader-n-StringBuilder派对。前者代码少,具有正确的错误处理并服从服务器发送的字符编码。 – 2012-03-31 09:27:12