我正在尝试在 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");
但是最后两行抛出一个错误,说找不到变量。这在Java中是不可能的吗?我知道在这种情况下使用相同类型声明一个变量(在条件之外声明它并在条件内部初始化它),但在这种情况下,类型根据条件不同。
作为参考,到目前为止,这是我的课程:
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 += "&";
}
}
}
}