摘要: 本文主要探讨在 Java 编程环境中对响应(Response)返回值的获取相关技术与方法。重点阐述了在不同场景下如何有效地获取和利用 Response 返回值,以实现高效的数据交互与程序逻辑控制。
一、引言
二、常见的获取 Response 返回值的方式
(一)基于 HTTP 的网络交互
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class ResponseValueRetrieval {
public static void main(String[] args) {
try {
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;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine())!= null) {
response.append(inputLine);
}
in.close();
// 此时 response 就是获取到的返回值(通常是 JSON 或者其他文本格式)
System.out.println(response.toString());
} else {
System.out.println("GET request not worked");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
(二)在 Web 服务框架中的应用
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@GetMapping("/data")
public ResponseEntity<String> getData() {
String data = "Some data to return";
return new ResponseEntity<>(data, HttpStatus.OK);
}
}
三、对返回值的处理
(一)JSON 数据
import com.fasterxml.jackson.databind.ObjectMapper;
// 假设 responseString 是获取到的 JSON 格式的返回值字符串
ObjectMapper objectMapper = new ObjectMapper();
MyObject myObject = objectMapper.readValue(responseString, MyObject.class);