在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`
@Autowiredprivate RestTemplate restTemplate;public String getApiResponse() {String url = "http://example.com/api";HttpHeaders headers = new HttpHeaders();HttpEntityentity = new HttpEntity<>(headers); ResponseEntityresponse = restTemplate.exchange(url, HttpMethod.GET, entity, String.class); return response.getBody();}
使用异步接口
AsyncService service = new AsyncServiceImpl();service.doAsyncOperation(new AsyncCallback() {@Overridepublic void onComplete(Object result) {System.out.println("Result: " + result);}@Overridepublic void onError(Exception e) {e.printStackTrace();}});
返回文件流
public interface FileService {InputStream getFileStream();}public class FileServiceImpl implements FileService {@Overridepublic InputStream getFileStream() {try {File file = new File("file_path");return new FileInputStream(file);} catch (FileNotFoundException e) {e.printStackTrace();}return null;}}
根据客户端选择的字段返回数据
@Autowiredprivate OrderServiceImpl orderService;@PostMapping("/test")public Listtest(@RequestBody RequestParamVO paramVO) { return orderService.getOrderList(paramVO);}@Datapublic class RequestParamVO {private Listfields; // 用户选择返回的字段 }

