我是客户端开发人员,转向服务器端开发。 我遇到的一个常见问题是需要进行一次API调用(例如获取身份验证令牌),然后进行后续API调用以获取我想要的数据。有时候,我需要连续为数据进行两次API调用,而不需要使用身份验证令牌。
是否有通用设计模式或Java库来解决此问题?或者我是否需要在每次需要时手动创建调用字符串?
编辑:我希望看起来像这样的东西
CustomClassBasedOnJson myStuff = callAPI("url", getResponse("authURL"));
这将使用从“authURL”收到的数据调用“url”。 这里的要点是我正在串联多个url调用,使用一个调用的结果来定义下一个调用。
答案 0 :(得分:1)
进行服务器端编程时,可以同步调用HTTP调用。
因此,正确的模式是简单地进行第一次调用,接收结果,然后在下一行中使用它。除非在http调用之间发生重大处理,否则无需将调用分成单独的线程或异步调用。
例如:
JsonResponseEntry getJsonReportResponse() throws IOException {
String sReportURL = "https://someurl.com/v2/report/report?" +
"startts=" + getDateYesterday("ts") +
"&endts=" + getDateNow("ts") +
"&auth=" + getAuthCode();
URL reportURL = new URL(sReportURL);
URLConnection conn = reportURL.openConnection();
BufferedReader buf = new BufferedReader(new InputStreamReader(conn.getInputStream()));
ObjectMapper mapper = new ObjectMapper();
JsonNode reportResult = mapper.readTree(buf);
return convertJSonNodeToJsonResponseEntry(reportResult);
}
String getAuthCode() throws IOException {
String sReportURL = "https://someurl.com/auth";
URL reportURL = new URL(sReportURL);
HttpURLConnection conn = (HttpURLConnection) reportURL.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
String urlParameters = "username=myUserName&password=mypassword";
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
BufferedReader buf = new BufferedReader(new InputStreamReader(conn.getInputStream()));
ObjectMapper mapper = new ObjectMapper();
AuthResponse response = mapper.readValue(buf, AuthResponse.class);
return response.toString();
}
在需要响应的URL调用中同步调用函数getAuthCode()。