如何判断真假?使用执行器,但成功似乎并没有改变它的价值..有什么技巧可以以“简单”的方式实现它吗?我能够到达 try catch 内部,但似乎它无法正常工作,我没有真正改变它的值..也许如果我将成功作为班级的一个属性? Chatgpt 处于疯狂模式,似乎无法解决我的问题..
public Boolean POST(String payload, String action) {
AtomicReference<Boolean> success = new AtomicReference<Boolean>(false);
executor.execute(() -> {
try {
Gson gJSON = new Gson();
// Convert payload to a JSON object
JSONObject jsonObject = new JSONObject(payload);
// Add the action property to the JSON object
jsonObject.put("action", action);
// Convert the modified JSON object back to a string
String payloadWithAction = gJSON.toJson(jsonObject);
//System.out.println("Payload to SV"+payloadWithAction);
// Create URL object
URL url = new URL("https://moveroute.org/php/run-register-api.php");
// Open connection
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
Response responseObject = new Response();
// Write JSON data to connection
try (OutputStream os = connection.getOutputStream()) {
os.write(payloadWithAction.getBytes());
}
// Check response code
int responseCode = connection.getResponseCode();
StringBuilder response = new StringBuilder();
Response responseJSON = null;
if (responseCode == HttpURLConnection.HTTP_OK) {
// Handle success
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String jsonResponse = response.toString();
//System.out.println("Response from server: " + jsonResponse);
responseJSON = gJSON.fromJson(jsonResponse, Response.class);
success.set(responseJSON.getStatus().booleanValue());
System.out.println(responseJSON.getMessage());
} else {
//ERROR FAIL
responseObject.setStatus(false);
responseObject.setMessage("Impossible to make the requested action.");
}
// Close connection
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
});
return success.get();
}
只是进行应用程序的登录
你总是得到 false 的原因是因为你的登录代码与你的“返回”线程运行在不同的线程(执行者线程)上,所以你不能保证你的返回代码将在完成登录部分之后执行,我认为如果你运行多次,你可能会得到正确的结果。有很多选项可以解决这个问题,但我认为根据您当前的实现,最好的方法是使用 futures:
class MyClass {
private Future<Boolean> post(String payload, String action) {
return executor.submit(() -> {
// your login code
// ..
return responseJSON.getStatus().booleanValue();
});
}
}
然后你可以像这样调用该方法:
MyClass myClass = new MyClass();
if(myClass.post("Hello", "World").get()) {
System.out.println("True is returned");
}
else {
System.out.println("False is returned");
}
如果不是出于学习目的,我认为没有任何理由不使用本机 HttpClient 或任何其他第三方库,例如:OkHttpClient、Apache HttpClient、Spring Web Client,还有更多,有些甚至支持异步请求,您可以使用这些库可以利用,我个人不会在没有http客户端的情况下发布请求,我认为你自己编写输出流是多余的,专注于你的业务逻辑并让其他库发挥他们的魔力。