简体   繁体   English

如何从服务器获取回声

[英]How to get echo from server

I'm trying to get an echo reply from my server. 我正在尝试从服务器获取回显回复。 The purpose of this is to check for internet connection and also to check the server status. 这样做的目的是检查Internet连接并检查服务器状态。 If I get a reply, a dialog box will appear with a simple message. 如果我得到答复,将出现一个对话框,其中包含一条简单消息。 Same goes with not getting a reply. 同样没有得到答复。

The dialog box appeared when I get a reply, but it won't appear when I don't get a reply. 当我收到答复时,将出现该对话框,但当我未收到答复时,将不会显示该对话框。

In my uploadDB.class, I have multiple cases that will perform different function in the PHP file. 在我的uploadDB.class中,我有多种情况将在PHP文件中执行不同的功能。 One of the case is a "ping" function and the other is an "updatecounter" function. 一种情况是“ ping”功能,另一种情况是“ updatecounter”功能。

When I remove the "updatecounter" case in my uploadDB.class, everything seems to work. 当我在我的uploadDB.class中删除“ updatecounter”案例时,一切似乎都可以正常工作。 Due to my requirements, I'm not supposed to remove the "updatecounter" case. 根据我的要求,我不希望删除“ updatecounter”案例。

Can someone advise me on how to solve this? 有人可以建议我如何解决这个问题吗?

Below are my codes and error in Logcat. 以下是我在Logcat中的代码和错误。

PHP file PHP文件

        if (isset($_POST['type'])){
        if ($_POST['type'] == "ping"){
        echo "success";
        }

MainActivity.class MainActivity.class

public boolean isInternetConnected = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        pingTask();
    }

    private void pingTask() {
        new uploadDB(new uploadDB.returnResult() {
            @Override
            public void onFinish(String result) {
                if (result.equalsIgnoreCase("success")) {
                    isInternetConnected = true;
                    showdialog("Server Status", "Working");
                } else {
                    isInternetConnected = false;
                    showdialog("Server Status", "Not Working");
                }
            }
        }).execute("ping");
    }

uploadDB.class uploadDB.class

protected String doInBackground(String... params) {
        String method = params[0];
        String data = "";
        String link = "www.example.com/example.php";

        switch (method){
            case "ping": {
                try{
                    data = URLEncoder.encode("type", "UTF-8") + "=" + URLEncoder.encode("ping", "UTF-8");
                    Log.e(TAG,"DATA: " + data);
                }catch (UnsupportedEncodingException e){
                    Log.e(TAG, "UnsupportedEncodingException: " + e.toString());
                }
                try {
                    URL url = new URL(link);
                    HttpURLConnection h = (HttpURLConnection) url.openConnection();
                    h.setDoInput(true);
                    h.setDoOutput(true);
                    OutputStreamWriter owriter =
                            new OutputStreamWriter(h.getOutputStream());
                    owriter.write(data);
                    owriter.flush();
                    BufferedReader b = new BufferedReader
                            (new InputStreamReader(h.getInputStream(), "UTF-8"), 8);
                    StringBuilder builder = new StringBuilder();
                    String line;
                    while ((line = b.readLine()) != null) {
                        builder.append(line);
                    }
                    return builder.toString();
                } catch (IOException e) {
                    Log.e(TAG, "IOException: " + e.toString());
                }
            }

          case "updatecounter": {
                String macAddress = params[1];
                String sensorname = params[2];
                String counter = params[3];
                try {
                    data = URLEncoder.encode("type", "UTF-8") + "=" + URLEncoder.encode("counter", "UTF-8")
                            + "&" + URLEncoder.encode("gate_name", "UTF-8") + "=" + URLEncoder.encode(sensorname, "UTF-8")
                            + "&" + URLEncoder.encode("mac", "UTF-8") + "=" + URLEncoder.encode(macAddress, "UTF-8")
                            + "&" + URLEncoder.encode("counter", "UTF-8") + "=" + URLEncoder.encode(counter, "UTF-8");
                    Log.e(TAG,"DATA: " + data);
                } catch (UnsupportedEncodingException e) {
                    Log.e(TAG, "UnsupportedEncodingException: " + e.toString());
                }

                try {
                    URL url = new URL(link);
                    HttpURLConnection h = (HttpURLConnection) url.openConnection();
                    h.setDoInput(true);
                    h.setDoOutput(true);
                    OutputStreamWriter owriter =
                            new OutputStreamWriter(h.getOutputStream());
                    owriter.write(data);
                    owriter.flush();
                    BufferedReader b = new BufferedReader
                            (new InputStreamReader(h.getInputStream(), "UTF-8"), 8);
                    StringBuilder builder = new StringBuilder();
                    String line;
                    while ((line = b.readLine()) != null) {
                        builder.append(line);
                    }
                    return builder.toString();
                } catch (IOException e) {
                    //activity.isInternetConnected = false;
                    Log.e(TAG, "IOException: " + e.toString());
                }
            }

Error in Logcat Logcat错误

Process: com.example.postserver, PID: 21624
    java.lang.RuntimeException: An error occurred while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:353)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
        at java.util.concurrent.FutureTask.run(FutureTask.java:271)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
        at java.lang.Thread.run(Thread.java:764)
     Caused by: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
        at com.example.postserver.uploadDB.doInBackground(uploadDB.java:69)
        at com.example.postserver.uploadDB.doInBackground(uploadDB.java:16)

you need to add a break at the end of the case. 您需要在案例结尾处添加一个休息时间。 If you not add it, every case after that will be executed: 如果不添加它,则此后的每种情况都将执行:

   switch (method){
        case "ping": {
            try{
                data = URLEncoder.encode("type", "UTF-8") + "=" + URLEncoder.encode("ping", "UTF-8");
                Log.e(TAG,"DATA: " + data);
            }catch (UnsupportedEncodingException e){
                Log.e(TAG, "UnsupportedEncodingException: " + e.toString());
            }
            try {
                URL url = new URL(link);
                HttpURLConnection h = (HttpURLConnection) url.openConnection();
                h.setDoInput(true);
                h.setDoOutput(true);
                OutputStreamWriter owriter =
                        new OutputStreamWriter(h.getOutputStream());
                owriter.write(data);
                owriter.flush();
                BufferedReader b = new BufferedReader
                        (new InputStreamReader(h.getInputStream(), "UTF-8"), 8);
                StringBuilder builder = new StringBuilder();
                String line;
                while ((line = b.readLine()) != null) {
                    builder.append(line);
                }
                return builder.toString();
            } catch (IOException e) {
                Log.e(TAG, "IOException: " + e.toString());
            }
        }
        break;
    case "updatecounter": {

You can get Any Response from server in android studio By 您可以从android studio中的服务器获取任何响应

InputStream inputStream = httpURLConnection.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String dataResponse = "";
                String inputLine = "";
                while((inputLine = bufferedReader.readLine()) != null){
                    dataResponse += inputLine;
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();

After that You can Print out your Response 之后,您可以打印出您的回复

System.out.println(dataResponse);

Put That code After your Post Code 将该代码放在您的邮政编码之后

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM