Java如何使用HTTP请求
时间: 2023-04-07 19:03:25 浏览: 90
Java可以使用HttpURLConnection或者HttpClient来发送HTTP请求。其中,HttpURLConnection是Java自带的API,HttpClient是Apache提供的开源库。以下是使用HttpURLConnection发送GET请求的示例代码:
```java
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://www.example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
System.out.println(content.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
以上代码会向http://www.example.com发送一个GET请求,并输出响应内容。如果需要发送POST请求,可以使用HttpURLConnection的setRequestMethod("POST")方法,并设置请求体。
阅读全文