在Java中,獲取response的方法主要是通過使用HttpURLConnection或者HttpClient來發送HTTP請求,然后獲取服務器的響應數據。
使用HttpURLConnection獲取response的方法如下:
URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
String responseData = response.toString();
// 處理響應數據
} else {
// 處理請求失敗的情況
}
connection.disconnect();
使用HttpClient獲取response的方法如下:
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://example.com");
CloseableHttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
String responseData = EntityUtils.toString(entity);
// 處理響應數據
} else {
// 處理請求失敗的情況
}
response.close();
httpClient.close();
以上是兩種常用的獲取response的方法,具體使用哪種方法取決于你的需求和項目環境。