在Java中請求第三方接口可以通過使用HttpURLConnection或者使用第三方庫如OkHttp等來實現。以下是使用HttpURLConnection請求第三方接口的示例代碼:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("https://api.thirdparty.com/endpoint");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
上述代碼中通過創建URL對象并調用openConnection方法獲取HttpURLConnection對象,然后設置請求方法為GET,最后讀取響應內容并輸出。請注意,這只是一個簡單的示例,實際中可能需要根據接口的要求設置請求頭、請求參數等。