I want to send a formbody using okhttp in java from the Android APP client-side to check if new file is available on the server, and handle this request through a PHP script on AWS EC2 server to send the URL to the new file back to APP.
Client side code:
@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;
}
Server side code:
<?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);
?>
The error I got:
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
What I have tried
- I have changed timeout duration to 2 minutes in OkHttpClient builder - it still throws errors
- I have made sure that the php script does work by navigating to it directly - I got the expected response in the browser
- I have added inbound and outbound rules for HTTPS on AWS ec2 instance
- I have tried and change the timeout duration to 5 minutes but my APP crashed due to "runtime abort" somehow.
My questions are:
- Is there anything to do with my server on this specific issue? Am I supposed to set up my server for okhttp client in some way?
- Is there anything else I could try to solve this problem? Or any possible reason you guys think that can cause it?
Thank you!!