java发起http请求代码
时间: 2024-01-02 21:16:38 浏览: 71
Sure, here's an example Java code for sending an HTTP request:
```
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class HTTPRequestExample {
public static void main(String[] args) throws Exception {
URL url = new URL("http://example.com"); // URL to send request to
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET"); // or "POST" if you want to send POST request
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Response code: " + responseCode);
System.out.println("Response body: " + response.toString());
}
}
```
This code sends a GET HTTP request to `http://example.com` and prints out the response code and body. You can modify it to send different types of requests, such as POST requests, by adjusting the `setRequestMethod()` method.
阅读全文