public static byte[] sendRequest(String url ,Object params ,boolean isHttps){
if(isHttps){
HttpsURLConnection urlConnection = (HttpsURLConnection)newURL(url).openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(60000);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
}
}else{
HttpURLConnection urlConnection = (HttpURLConnection)new URL(url).openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(60000);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
}
}
在这种情况下, if 和 else 都包含除了类型转换之外的相同代码行。如果我再次将这行代码移动到一个通用方法中,我想键入 cast 并再次执行此过程。我怎样才能减少这些多余的行,任何人都可以帮助我。
我在 python 中有一个解决方案。
//pseudo code .
if(isHttps) :
urlConnection = https .
else :
urlConnection = http .
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(60000);
因为在 if 内部的 python 变量中,也可以从外部 block 访问。在java中我该怎么做。