在Java中编写接口返回数据通常有以下几种方法:
使用`HttpURLConnection`
URL url = new URL("http://example.com/api");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
}
使用`HttpClient`
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://example.com/api");
CloseableHttpResponse response = httpClient.execute(httpGet);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity);
System.out.println(result);
}
} finally {
response.close();
}
使用`RestTemplate`
@Autowired
private RestTemplate restTemplate;
public String getApiResponse() {
String url = "http://example.com/api";
HttpHeaders headers = new HttpHeaders();
HttpEntity
entity = new HttpEntity<>(headers); ResponseEntity
response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class); return response.getBody();
}
使用异步接口
AsyncService service = new AsyncServiceImpl();
service.doAsyncOperation(new AsyncCallback() {
@Override
public void onComplete(Object result) {
System.out.println("Result: " + result);
}
@Override
public void onError(Exception e) {
e.printStackTrace();
}
});
返回文件流
public interface FileService {
InputStream getFileStream();
}
public class FileServiceImpl implements FileService {
@Override
public InputStream getFileStream() {
try {
File file = new File("file_path");
return new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
根据客户端选择的字段返回数据
@Autowired
private OrderServiceImpl orderService;
@PostMapping("/test")
public List
test(@RequestBody RequestParamVO paramVO) { return orderService.getOrderList(paramVO);
}
@Data
public class RequestParamVO {
private List
fields; // 用户选择返回的字段 }