I have to declare a variable, the type of this variable depends on a parameter, so I have an if clause and define this variable there:
if(this.httpMethod == "POST"){
HttpPost request = new HttpPost(url);
}
if(this.httpMethod == "GET"){
HttpGet request = new HttpGet(url);
}
The problem is that in Java, the scope of that variable lies inside the if, so I can't use it later !. If I try:
request.addHeader("Accept", "application/json");
That gives me: request cannot be resolved
So, the question would be: how can I define a variable, that it's type depends on a parameter.
What I have tried:
- Setting the variable to final.
My current solution is to duplicate the code, inside every if clause, I set the same Headers, Connection, grab the response, .... So, of course, I don't like this.
Design. I have this HTTP request class like this, so I can use it to handle the request, so, I just have to send it some parameters (URL, method, authentication, ...) , and it will give me back the result. This class is my bottom layer of my Android app, that looks like this:
- Activities.java (all the activities)
- Core.java (handle resources)
- HttpRequest.java (handle internet resources)
if(this.httpMethod.equals("POST")). use .equals to compare strigns