java url get
时间: 2023-11-24 13:07:38 浏览: 31
To perform a HTTP GET request in Java, you can use the HttpURLConnection class. Here is an example:
```
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class HttpGetExample {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
In this example, we are performing a GET request to "http://example.com" and setting the "Accept" header to "application/json". We then check the response code to make sure it is 200 (OK), and print out the response from the server. Finally, we disconnect the HttpURLConnection.