如何解决Java OOP设计如何重用http客户端
public class BertClient {
public static List<Float> encodeText(String text) throws IOException {
String url = "http://127.0.0.1:5000/encode";
List<Float> bertVector = sendPOST(url,text);
return bertVector;
}
private static List<Float> sendPOST(String url,String text) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
String requestBody = String.format("{\"text\":\"%s\"}",text);
StringEntity requestEntity = new StringEntity(requestBody);
// send a JSON data
httpPost.setEntity(requestEntity);
httpPost.setHeader("Accept","application/json");
httpPost.setHeader("Content-type","application/json");
CloseableHttpResponse response = httpClient.execute(httpPost);
InputStream source = response.getEntity().getContent(); //Get the data in the entity
Reader reader = new InputStreamReader(source);
Gson gson = new Gson();
JsonResponse json = gson.fromJson(reader,JsonResponse.class);
httpClient.close();
return json.bert_vector;
}
private class JsonResponse {
//This class is for Gson to parse JSON response into Object
//This variable needs to match the key in JSON response,so it's not camel case
private List<Float> bert_vector;
}
}
这更多是一个设计问题。
我对Java比较陌生,我写了这个包,以便可以导入它并在其他地方使用。我所需要的只是使用BertClient.encodeText()
发送POST请求并在其他Java文件中获得响应,因此,我认为不必实例化此类。我可以调用该方法。然后我意识到,使用此代码,每次发送POST请求时,我都会构建一个新的httpClient,这显然是我猜错了吗?
URL现在已经过硬编码以进行测试,但稍后将通过此类中的方法检索,并读取我存储在AWS Secrets Manager中的URL。
我想知道如何设计此类,以便其重用代码并且不会创建不必要的新对象?
请在原始代码上使用修改后的示例代码进行解释。
我也不确定我的问题标题是否正确,很难给它提供正确的名称,因此,如果您有任何建议,我会进行更改。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。