【发布时间】:2021-03-16 23:44:41
【问题描述】:
在给定的情况下,我必须在 Android 上发送一条 POST 消息,我希望它继续尝试直到完成。我的理解是设置:
urlConnection.setConnectTimeout(0);
会一直尝试连接直到它通过,但实际发生的是 try 块失败,而是抛出 UnknownHostException:
private class SendAlert extends AsyncTask<String, String, String> {
protected String doInBackground(String... strings) {
Log.d(TAG, "sendAlarm: sending alarm");
String stringUrl = createUri();
HttpsURLConnection urlConnection = null;
BufferedReader reader = null;
String postData = "";
Log.d(TAG, "sendAlarm: apikey: " + apiKey);
try{
Log.d(TAG, "sendAlarm: trying");
URL finalURL = new URL(stringUrl);
urlConnection = (HttpsURLConnection)finalURL.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(0);
urlConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
urlConnection.setRequestProperty("Accept","application/json");
urlConnection.setRequestProperty("x-api-key",apiKey);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
int responseCode = urlConnection.getResponseCode();
Log.d(TAG, "doInBackground: response code = " + responseCode);
}catch (MalformedURLException e) {
e.printStackTrace();
Log.d(TAG, "doInBackground: error 1 " + e.toString());
}catch(UnknownHostException e){
Log.d(TAG, "doInBackground: e: " + e);
Log.d(TAG, "doInBackground: retrying");
}
catch(Exception e){
Log.d(TAG, "doInBackground: error 2 " + e.toString());
}
想知道在 Android 上设置发布消息的最佳方式是什么,即使手机处于飞行模式 5 小时,也要继续尝试连接直到连接成功。
编辑:@user3252344 的回答如下,直接在 AyncTask 的 catch 块中再次调用该函数是否有任何问题:
catch(UnknownHostException e){
Log.d(TAG, "doInBackground: e: " + e);
Log.d(TAG, "doInBackground: retrying");
SendAlarm sendAlarm = new SendAlarm;
sendAlarm.execute();
}
【问题讨论】:
标签: android post httpsurlconnection