简体   繁体   中英

Declaring a variable and its type in a conditional statement

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 += "&";
            }
        }
    }
}

This is a scope issue.

Change it to

public String sendRequest(String address) throws IOException {
   HttpURLConnection connection = null;
   //Only send the request if there is data to be sent!
   if (!data.isEmpty()) {
       if (this.ssl) {
         connection = (HttpsURLConnection) new URL(address).openConnection();
       } else {
         connection = (HttpURLConnection) new URL(address).openConnection();
       }
   }
   connection.setDoOutput(true);
   connection.setRequestMethod("POST");
   ...

You were attempting to access connection when it was being defined within an if statement. Ergo, nothing else had access to this variable.

See this. In java, how to create HttpsURLConnection or HttpURLConnection based on the url?

Basically since HttpsURLConnection extends HttpUrlConnection you don't need to declare in the if statement.

Your connection variables are declared within very short blocks and they are out of scope by the time you attempt to call methods on them.

Declare one connection variable before the block, and set it in each case, so that the variable is still in scope by that time you call methods on it.

HttpURLConnection connection;
if(this.ssl == true) {
    connection = (HttpsURLConnection) new URL(address).openConnection();
}
else {
    connection = (HttpURLConnection) new URL(address).openConnection();
}
connection.setDoOutput(true);
connection.setRequestMethod("POST");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM