java中发送http请求通过什么发送
时间: 2023-10-11 10:05:47 浏览: 32
在Java中发送HTTP请求可以使用多种方式,其中最常见的方式是使用Java的内置类库`java.net`或第三方库如Apache HttpClient。
使用`java.net`类库发送HTTP请求的示例如下:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpRequestExample {
public static void main(String[] args) {
try {
// 创建URL对象
URL url = new URL("http://example.com");
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法
connection.setRequestMethod("GET");
// 发送请求
int responseCode = connection.getResponseCode();
// 读取响应
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 输出响应结果
System.out.println("Response Code: " + responseCode);
System.out.println("Response Body: " + response.toString());
// 关闭连接
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
上述代码使用`HttpURLConnection`类发送GET请求,并输出响应结果。
另外,使用第三方库Apache HttpClient发送HTTP请求也非常常见。你可以通过添加Maven或Gradle依赖来使用Apache HttpClient。以下是一个使用Apache HttpClient发送GET请求的示例:
```java
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpRequestExample {
public static void main(String[] args) {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// 创建HttpGet对象
HttpGet httpGet = new HttpGet("http://example.com");
// 发送请求
CloseableHttpResponse response = httpClient.execute(httpGet);
// 读取响应
String responseBody = EntityUtils.toString(response.getEntity());
// 输出响应结果
System.out.println("Response Code: " + response.getStatusLine().getStatusCode());
System.out.println("Response Body: " + responseBody);
// 关闭响应
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这是一个使用Apache HttpClient发送GET请求的简单示例,它与`java.net`示例相似,但使用了不同的类和方法。