当前有代码在网络连接时成功向数据库提交数据。我的应用程序是一个可以在户外使用的应用程序,经常在服务非常差的地方使用。HTTP Post延迟至在线
我的问题是延迟HTTP Post的最佳方式是什么,直到存在活动的网络连接?我应该创建一个在没有连接时会运行的服务吗?传输的数据很小,大约一千字节,所以我可以让应用程序存储它直到设备在线,然后提交数据。这看起来可行吗?
另一个更穷的选择是让应用程序存储数据,并在每次启动数据时检查是否有任何数据仍在等待提交,并提供一个活动连接进行提交。
我目前需要提交数据的代码如下。如果您对此有任何建议,那么这些也不会受到欢迎。
String setPost(Context context)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(context.getResources().getString(R.string.url));
try
{
List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>(22);
nameValuePairs.add(new BasicNameValuePair("month", "7"));
... etc ...
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
InputStream is = response.getEntity().getContent();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(20);
int current = 0;
while ((current = bis.read()) != -1)
{
baf.append((byte)current);
}
Toast.makeText(context, "thank you for submitting!", Toast.LENGTH_LONG).show();
return new String(baf.toByteArray());
}
catch (ClientProtocolException e)
{
Log.e(this.toString(), "fail: " + e);
Toast.makeText(context, "submission failed :(\n please report the error below to developer\n" + e.toString(), Toast.LENGTH_LONG).show();
return ("fail: " + e);
}
catch (IOException e)
{
Log.e(this.toString(), "fail: " + e);
Toast.makeText(context, "submission failed :(\n please report the error below to developer:\n" + e.toString(), Toast.LENGTH_LONG).show();
return ("fail: " + e);
}