在Java中,当你需要从Response对象中获取返回值时,可以使用以下方法:
- 首先,确保你已经导入了相关的库。例如,如果你使用的是
java.net.HttpURLConnection
,则需要导入以下包:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
- 创建一个方法来发送HTTP请求并获取响应:
public static String sendGetRequest(String urlString) throws Exception {
URL url = new URL(urlString);
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 content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
connection.disconnect();
return content.toString();
} else {
throw new Exception("Failed to get response from the server. Response code: " + responseCode);
}
}
- 调用该方法并传入URL字符串以获取响应内容:
public static void main(String[] args) {
try {
String url = "https://api.example.com/data";
String response = sendGetRequest(url);
System.out.println("Response: " + response);
} catch (Exception e) {
e.printStackTrace();
}
}
这样,你就可以从Response对象中获取返回值了。注意,这里的示例仅适用于GET请求。如果你需要处理其他类型的HTTP请求(如POST、PUT等),你需要对代码进行相应的修改。
标签:JAVA,String,java,connection,new,返回值,Response,HttpURLConnection From: https://blog.51cto.com/u_16390833/12090754