在Java中实现GET请求可以使用HttpURLConnection类来实现。以下是一个简单的示例:
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpGetRequest { public static void main(String[] args) { try { URL url = new URL("http://example.com/api"); 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,并发送请求。最后读取响应内容并输出到控制台。