I'm trying to do this in Java:
if(this.ssl == true) {
HttpsURLConnection connection = (HttpsURLConnection) new URL(address).openConnection();
}
else {
HttpURLConnection connection = (HttpURLConnection) new URL(address).openConnection();
}
connection.setDoOutput(true);
connection.setRequestMethod("POST");
But the last two lines are throwing an error saying that the variable can't be found. Is this not possible in Java? I know about declaring a variable in this situation with the same type (declaring it outside the conditional and initializing it inside the conditional) but in this case the type is not the same based on the condition.
For reference, here is my class so far:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import javax.net.ssl.HttpsURLConnection;
public class Post {
private String data;
private boolean ssl;
public Post(boolean ssl) {
this.ssl = ssl;
}
public String sendRequest(String address) throws IOException {
//Only send the request if there is data to be sent!
if (!data.isEmpty()) {
if (this.ssl == true) {
HttpsURLConnection connection = (HttpsURLConnection) new URL(address).openConnection();
} else {
HttpURLConnection connection = (HttpURLConnection) new URL(address).openConnection();
}
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(data);
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
reader.close();
writer.close();
return response.toString();
} else {
return null;
}
}
public void setData(String[] keys, String[] values) throws UnsupportedEncodingException {
//Take in the values and put them in the right format for a post request
for (int i = 0; i < values.length; i++) {
this.data += URLEncoder.encode(keys[i], "UTF-8") + "=" + URLEncoder.encode(values[i], "UTF-8");
if (i + 1 < values.length) {
this.data += "&";
}
}
}
}