0

我想从 Android APP 客户端使用 java 中的 okhttp 发送一个表单体,以检查服务器上是否有新文件,并通过 AWS EC2 服务器上的 PHP 脚本处理此请求,以将新文件的 URL 发送回应用程序。

客户端代码:

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    static ResponseBody requestUpdate(Long name){
        Log.d(TAG, "requestUpdate: method starts");
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60,TimeUnit.SECONDS)
                .writeTimeout(60,TimeUnit.SECONDS)
                .build();

        String fileName = Long.toString(name);
        RequestBody formBody = new FormBody.Builder()
                .add("name", fileName)
                .build();
        Request request = new Request.Builder()
                .url("https://url_to_aws_ec2_server/handleRequest.php")
                .post(formBody)
                .build();

        try (Response response = client.newCall(request).execute()) {
            Log.d(TAG, "requestUpdate: execute success");
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            System.out.println(response.body().string());
            return response.body();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

服务器端代码:

<?php
    header("Content-Type: application/json"); 

    $fileClient = pathinfo($_POST['name'], PATHINFO_FILENAME);
    $filedir = "./uploads/";

    // acquire the lastest file on server
    if(is_dir($filedir))
        {
            $fl=scandir($filedir);
            foreach($fl as $value){
                if($value !="." && $value!=".." && pathinfo($value, PATHINFO_EXTENSION) == "mp4"){
                    if(strcmp($value, $fileServer)>0){
                        $fileServer = $value;
                    }    
                }
            }
            // compare it with the one from client side
            if (strcmp($fileClient, $fileServer)>=0){
                $response['success'] = TRUE;
                $response['flag'] = 0;
            }else{
                $response['success'] = TRUE; 
                $response['flag'] = 1;
                $response['link'] = sprintf("http://url_to_ec2_server/%s", $fileServer);
            }
        }
        else{
            $response['success'] = FALSE;
            echo("Your directory does not exist.");
        }

    echo json_encode($response);
?>

我得到的错误:

2020-08-25 15:01:28.574 2523-2579/com.example.ses_adplatform_test W/System.err: 
java.net.SocketTimeoutException: 
failed to connect to url_to_aws_ec2_server/13.59.157.98 (port 443) from /10.0.2.16 (port 54238) after 60000ms

我试过的

  1. 我已在 OkHttpClient 构建器中将超时持续时间更改为 2 分钟 - 它仍然会引发错误
  2. 我已经通过直接导航到它来确保 php 脚本确实有效 - 我在浏览器中得到了预期的响应
  3. 我在 AWS ec2 实例上添加了 HTTPS 的入站和出站规则
  4. 我已尝试将超时持续时间更改为 5 分钟,但我的 APP 由于“运行时中止”以某种方式崩溃。

我的问题是:

  1. 在这个特定问题上与我的服务器有什么关系吗?我应该以某种方式为 okhttp 客户端设置我的服务器吗?
  2. 还有什么我可以尝试解决这个问题的吗?或者你们认为可能导致它的任何可能原因?

谢谢!!

4

0 回答 0