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");
}
}
In this both if and else contains same lines of code beside type casting . If I move this lines of code to a common method again I want to type cast and do this process again . How can i reduce this redudant lines can anyone help me .
I have a solution in 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);
Because in python variable inside a if also accessible from outside block . In java how can i do this .
I assume that the
isHttpsvariable check is there for a reason(?) and therefore the second cast should actually beHttpURLConnection, meaning there is a typo in the question?If so the most methods used in the question are available in the parent class
URLConnectionwithout a cast, but not all.Fortunately HttpsURLConnection is a subclas of HttpUrlConnection so just always casting to that will work here, replace all with (no need for the isHttps check):