0

我想每 3 分钟向服务器发送一个字符串。我正在使用以下代码将数据从 android 手机发送到服务器:

String stringDatatoSend="Hii server";
HttpEntity entity;
HttpClient client = new DefaultHttpClient();
String url ="http://some IP/android/insert.php";
HttpPost request = new HttpPost(url);
StringEntity se = new StringEntity(stringDatatoSend);
se.setContentEncoding("UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
entity = se;
request.setEntity(entity);
HttpResponse response = client.execute(request);
entity = response.getEntity();

但是,如果服务器关闭,数据就会丢失,因为无论是否有任何确认都会发送数据。如何
在发送数据之前检查服务器是否处于活动状态以避免数据丢失。我尝试了以下代码,但它总是返回 false。

public boolean isConnectedToServer() {
    try {
        if(InetAddress.getByName("http://some IP/android/insert.php").isReachable(50000)) {
            return true;
        } else {
            return false;
        }
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        return false;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        return false;
    }
}

我也有这两个选项:

netAddress address = InetAddress.getByName(HOST_NAME);
boolean  reachable = address.isReachable(timeout);

并通过使用运行时:

Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("ping www.google.com");

主机名 ip 或地址应该是什么。

4

3 回答 3

0

You need to send data again after every 3 minutes, You can't actually control if server is responding or not, or your device's network performance. But you can control the calls you are making to the server. If you are not getting data acknowledgement it means your data is not yet received by the server and you need to send it again. Just check the acknowledgement of data receive from server and then send/resend data.

于 2013-10-15T05:36:20.230 回答
0

用于检查服务器是否已关闭。您可以使用以下代码:

try {
        String response_string = null;
        HttpPost get = new HttpPost(SERVER_URL);
        HttpClient hc = new DefaultHttpClient();
        HttpResponse rp = hc.execute(get);
        response_string = new StringBuffer(EntityUtils.toString(rp.getEntity()));

        Log.d("Json Response  = ", "" + response_string);
        return response_string.toString();
    } catch (SocketException e) {
        e.printStackTrace();
    } catch (ConnectTimeoutException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
于 2013-10-15T06:35:04.653 回答
0

每 3 分钟后,您需要检查互联网连接(如果可用)然后点击 url 或等待接下来的 3 分钟:

public  boolean checkInternetConnection() {

    ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    if (conMgr.getActiveNetworkInfo() != null
            && conMgr.getActiveNetworkInfo().isAvailable()
            && conMgr.getActiveNetworkInfo().isConnected()) {
        Log.d("Internet Connection  Present","");
        isFound=true;
    } else {
        Log.d("Internet Connection Not Present","");
        isFound= false;
    }
    return isFound;
}
于 2013-10-15T05:24:38.780 回答