http调用接口

发布时间 2023-12-21 16:10:35作者: 皇问天
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public static String get(String url, String cookie) throws IOException {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("GET");

// 设置 Cookie
connection.setRequestProperty("Cookie", cookie);

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);
response.append("\n");
}
reader.close();
return response.toString();
} else {
throw new IOException("Request failed with HTTP status: " + responseCode);
}
}