用java发送一个http请求,这个问题
时间: 2024-05-09 11:20:40 浏览: 7
可以使用Java中的URLConnection或HttpClient来发送HTTP请求。
使用URLConnection发送HTTP请求的示例代码:
```
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class HttpUrlConnectionExample {
public static void main(String[] args) throws Exception {
String url = "http://example.com";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法
con.setRequestMethod("GET");
// 发送请求
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
// 读取响应内容
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.toString());
}
}
```
使用HttpClient发送HTTP请求的示例代码:
```
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class HttpClientExample {
public static void main(String[] args) throws Exception {
String url = "http://example.com";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
// 发送请求
HttpResponse response = client.execute(request);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
// 读取响应内容
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
// 打印响应内容
System.out.println(result.toString());
}
}
```