我正在尝试用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 += "&";
}
}
}
}
答案 0 :(得分:3)
这是一个范围问题。
将其更改为
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");
...
在connection
语句中定义时,您试图访问if
。因此,没有其他任何东西可以访问这个变量。
答案 1 :(得分:2)
看到这个。 In java, how to create HttpsURLConnection or HttpURLConnection based on the url?
基本上,由于HttpsURLConnection
扩展HttpUrlConnection
,您不需要在if语句中声明。
答案 2 :(得分:0)
您的connection
变量在非常短的块中声明,并且在您尝试调用它们的方法时它们超出了范围。
在块之前声明一个connection
变量,并在每种情况下设置它,以便在您调用方法时变量仍在范围内。
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");