我有一个基于httpURLConnection的同步代码,我必须将其转换为异步模式。 基本同步模式功能齐全,可以正常工作。为了使其以异步方式实现,我尝试将HttpClient与sendAsync方法(JDK11)结合使用。但是我被困住了。
项目摘要,如下所示: 1)几个测试类,它们扩展了abstractAPITest类。 2)这个abstractAPITest类具有建立连接的功能,现在我正在处理它。 3)class调用测试类的用户 4)主类,它在多个线程中创建User实例并运行它们。
可能应该将打开的连接功能移到User类或Main类中? idk。
这是我最初的内容(同步):
byte[] sendRequest(JSONObject jsonObject, String username, String password) throws IOException, URISyntaxException {
HttpURLConnection httpURLConnection = (HttpURLConnection) (new URL(this.apiUrl)).openConnection();
if (username != null && password != null) {
String userPassword = username + ":" + password;
httpURLConnection.setRequestProperty("Authorization", "Basic " + DatatypeConverter.printBase64Binary(userPassword.getBytes()));
}
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.setDoOutput(true);
DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
dataOutputStream.write(jsonObject.toString().getBytes());
dataOutputStream.flush();
log.info("REST send: JSONObject");
if (httpURLConnection.getResponseCode() != 200) {
log.error("REST send error");
throw new IOException();
} else {
byte[] responseBody = null;
StringBuilder data = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
data.append(line);
responseBody = data.toString().getBytes();
}
br.close();
return responseBody;
}
}
以及我的异步状态:
byte[] request = jsonObject.toString().getBytes();
String userPassword;
if (username != null && password != null) {
userPassword = username + ":" + password;
} else {
throw new NullPointerException("No username and/or password.");
}
byte[] responseBody = null;
byte[] request = jsonObject.toString().getBytes();
var client = HttpClient.newHttpClient();
var httpRequest = HttpRequest.newBuilder()
.uri(new URI(apiUrl))
.version(HttpClient.Version.HTTP_2)
.header("Content-Type", "application/json")
.header("Authorization", "Basic " + DatatypeConverter.printBase64Binary(userPassword.getBytes()))
.POST(HttpRequest.BodyPublishers.ofByteArray(request))
.build();
HttpResponse.BodyHandler<String> bodyHandler = HttpResponse.BodyHandlers.ofString();
CompletableFuture<HttpResponse<String>> future = client.sendAsync(httpRequest, bodyHandler);
future.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join();
byte[] responseBody = null; // DON'T PAY ATTENTION
return responseBody; // TO THESE TWO LINES
}
private static String basicAuthorization(String username, String password) {
String userPassword = null;
if (username != null && password != null) {
userPassword = username + ":" + password;
}
return "Basic " + DatatypeConverter.printBase64Binary(userPassword.getBytes());
}
所以我需要异步方法与同步方法一样,但是异步。那我下一步该怎么办?