Java可以通过以下方式发起HTTP请求:

1.使用Java内置的HttpURLConnection类

HttpURLConnection是一个基于HTTP协议的URLConnection类,可以用来发送HTTP请求和接收HTTP响应。可以通过以下步骤发起HTTP请求:

1)创建一个URL对象,参数为请求地址。

2)调用URL对象的openConnection方法,获得HttpURLConnection对象。

3)设置HttpURLConnection的请求方法(GET或POST)、请求头、请求体等参数。

4)发送请求,获取响应码、响应头和响应体。

5)关闭连接。

示例代码:

URL url = new URL("http://www.example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
int responseCode = connection.getResponseCode();
Map<String, List<String>> headers = connection.getHeaderFields();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
    response.append(line);
}
reader.close();
connection.disconnect();

2.使用第三方库Apache HttpComponents

Apache HttpComponents是一个开源的HTTP客户端库,可以用来发送HTTP请求和接收HTTP响应。可以通过以下步骤发起HTTP请求:

1)创建一个CloseableHttpClient对象。

2)创建一个请求对象,设置请求方法(GET或POST)、请求头、请求体等参数。

3)发送请求,获取响应对象。

4)从响应对象中获取响应码、响应头和响应体。

5)关闭连接。

示例代码:

CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://www.example.com");
httpGet.setHeader("User-Agent", "Mozilla/5.0");
CloseableHttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
Header[] headers = response.getAllHeaders();
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
response.close();
httpClient.close();

3.使用第三方库OkHttp

OkHttp是一个开源的HTTP客户端库,可以用来发送HTTP请求和接收HTTP响应。可以通过以下步骤发起HTTP请求:

1)创建一个OkHttpClient对象。

2)创建一个请求对象,设置请求方法(GET或POST)、请求头、请求体等参数。

3)发送请求,获取响应对象。

4)从响应对象中获取响应码、响应头和响应体。

5)关闭连接。

示例代码:

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
        .url("http://www.example.com")
        .header("User-Agent", "Mozilla/5.0")
        .build();
Response response = client.newCall(request).execute();
int statusCode = response.code();
Headers headers = response.headers();
String responseString = response.body().string();
response.close();
java如何发起http请求

原文地址: https://www.cveoy.top/t/topic/02z 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录