gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
HttpURLConnection获取返回数据
- User
HttpURLConnection获取返回数据
- Assistant
以下是使用HttpURLConnection获取返回数据的基本示例代码:
java
HttpURLConnection获取返回数据
以下是使用HttpURLConnection获取返回数据的基本示例代码:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpURLConnectionExample {
public static void main(String[] args) {
try {
// 创建URL对象
URL url = new URL("https://www.example.com/api");
// 创建HttpURLConnection对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法
connection.setRequestMethod("GET");
// 获取返回状态码
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 读取返回数据
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 打印返回数据
System.out.println("Response Data: " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
上述代码使用了HttpURLConnection发送GET请求,并读取返回的数据。请注意替换URL为实际的API地址。
Not yet included in a published release.