Java實現HTTP請求的4種方式總結
前言
在日常工作和學習中,有很多地方都需要發(fā)送HTTP請求,本文以Java為例,總結發(fā)送HTTP請求的多種方式
HTTP請求實現過程
GET??①、創(chuàng)建遠程連接
??②、設置連接方式(get、post、put…)
??③、設置連接超時時間
??④、設置響應讀取時間
??⑤、發(fā)起請求
??⑥、獲取請求數據
??⑦、關閉連接
POST??①、創(chuàng)建遠程連接
??②、設置連接方式(get、post、put。。。)
??③、設置連接超時時間
??④、設置響應讀取時間
??⑤、當向遠程服務器傳送數據/寫數據時,需要設置為true(setDoOutput)
??⑥、當前向遠程服務讀取數據時,設置為true,該參數可有可無(setDoInput)
??⑦、設置傳入參數的格式:(setRequestProperty)
??⑧、設置鑒權信息:Authorization:(setRequestProperty)
??⑨、設置參數
??⑩、發(fā)起請求
???、獲取請求數據
???、關閉連接
一、使用 HttpURLConnection 類
HttpURLConnection 是 Java 標準庫中用來發(fā)送 HTTP 請求和接收 HTTP 響應的類。
它預先定義了一些方法,如 setRequestMethod()、setRequestProperty() 和 getResponseCode(),方便開發(fā)者自由地控制請求和響應。
示例代碼:
import java.net.*;
import java.io.*;
public class HttpURLConnectionExample {
private static HttpURLConnection con;
public static void main(String[] args) throws Exception {
URL url = new URL("https://www.example.com");
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();
con.disconnect();
System.out.println(content.toString());
}
}二、使用 HttpClient 庫
HttpClient 是一個 HTTP 客戶端庫,提供了向 HTTP 服務器發(fā)送請求和處理響應的方法。
它支持多種請求協(xié)議,如 GET、POST 等,并允許開發(fā)者自由地設置請求頭、請求參數、連接池等。HttpClient 還提供了基于線程池的異步請求處理方式。
示例代碼:
import org.apache.http.HttpEntity;
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 HttpClientExample {
public static void main(String[] args) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("https://www.example.com");
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
EntityUtils.consume(entity);
System.out.println(result);
} finally {
response.close();
}
}
}三、使用 Okhttp 庫
Okhttp 是由 Square 公司開發(fā)的一款輕量級網絡請求庫,支持普通的 HTTP/1.1 和 SPDY,可與 Retrofit 等網絡請求框架搭配使用。
示例代碼:
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
public class OkhttpExample {
private static final OkHttpClient client = new OkHttpClient();
public static void main(String[] args) throws IOException {
Request request = new Request.builder()
.url("https://www.example.com")
.build();
try (Response response = client.newCall(request).execute()) {
String result = response.body().string();
System.out.println(result);
}
}
}四、使用 Spring 的 RestTemplate
RestTemplate 是 Spring 庫中用于訪問 REST API 的類,它基于 HttpMessageConverter 接口,可以將 Java 對象轉換為請求參數或響應內容。
RestTemplate 還支持各種 HTTP 請求方法、請求頭部定制、文件上傳和下載等操作。
示例代碼:
public class HttpTemplate {
public static String httpGet(String url) {
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.exchange(url, HttpMethod.GET, null, String.class).getBody();
return result;
}
public static String httpPost(String url, String name) {
RestTemplate restTemplate = new RestTemplate();
return restTemplate.postForEntity(url, name, String.class).getBody();
}
public static void main(String str[]) {
System.out.println(HttpTemplate.httpGet("https://www.example.com"));
System.out.println(HttpTemplate.httpPost("https://www.example.com", "ming"));
}
}??注:上述示例代碼,我們并沒有考慮網絡請求可能失敗的情況。在實際應用中,需要對異常進行捕獲和處理。
總結
以上就是今天要講的內容,本文僅僅簡單介紹了 Java 中常見的幾種發(fā)送 HTTP 請求的方式,可以根據實際需要選擇合適的方式。
到此這篇關于Java實現HTTP請求的4種方式總結的文章就介紹到這了,更多相關Java實現HTTP請求內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot中關于static和templates的注意事項以及webjars的配置
今天小編就為大家分享一篇關于SpringBoot中關于static和templates的注意事項以及webjars的配置,小編覺得內容挺不錯的,現在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-01-01
SpringBoot中的@EnableConfigurationProperties注解詳細解析
這篇文章主要介紹了SpringBoot中的@EnableConfigurationProperties注解詳細解析,如果一個配置類只配置@ConfigurationProperties注解,而沒有使用@Component或者實現了@Component的其他注解,那么在IOC容器中是獲取不到properties 配置文件轉化的bean,需要的朋友可以參考下2024-01-01

