Java實(shí)現(xiàn)HTTP請求的4種方式總結(jié)
前言
在日常工作和學(xué)習(xí)中,有很多地方都需要發(fā)送HTTP請求,本文以Java為例,總結(jié)發(fā)送HTTP請求的多種方式
HTTP請求實(shí)現(xiàn)過程
GET??①、創(chuàng)建遠(yuǎn)程連接
??②、設(shè)置連接方式(get、post、put…)
??③、設(shè)置連接超時(shí)時(shí)間
??④、設(shè)置響應(yīng)讀取時(shí)間
??⑤、發(fā)起請求
??⑥、獲取請求數(shù)據(jù)
??⑦、關(guān)閉連接
POST??①、創(chuàng)建遠(yuǎn)程連接
??②、設(shè)置連接方式(get、post、put。。。)
??③、設(shè)置連接超時(shí)時(shí)間
??④、設(shè)置響應(yīng)讀取時(shí)間
??⑤、當(dāng)向遠(yuǎn)程服務(wù)器傳送數(shù)據(jù)/寫數(shù)據(jù)時(shí),需要設(shè)置為true(setDoOutput)
??⑥、當(dāng)前向遠(yuǎn)程服務(wù)讀取數(shù)據(jù)時(shí),設(shè)置為true,該參數(shù)可有可無(setDoInput)
??⑦、設(shè)置傳入?yún)?shù)的格式:(setRequestProperty)
??⑧、設(shè)置鑒權(quán)信息:Authorization:(setRequestProperty)
??⑨、設(shè)置參數(shù)
??⑩、發(fā)起請求
???、獲取請求數(shù)據(jù)
???、關(guān)閉連接
一、使用 HttpURLConnection 類
HttpURLConnection 是 Java 標(biāo)準(zhǔn)庫中用來發(fā)送 HTTP 請求和接收 HTTP 響應(yīng)的類。
它預(yù)先定義了一些方法,如 setRequestMethod()、setRequestProperty() 和 getResponseCode(),方便開發(fā)者自由地控制請求和響應(yīng)。
示例代碼:
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 服務(wù)器發(fā)送請求和處理響應(yīng)的方法。
它支持多種請求協(xié)議,如 GET、POST 等,并允許開發(fā)者自由地設(shè)置請求頭、請求參數(shù)、連接池等。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ā)的一款輕量級網(wǎng)絡(luò)請求庫,支持普通的 HTTP/1.1 和 SPDY,可與 Retrofit 等網(wǎng)絡(luò)請求框架搭配使用。
示例代碼:
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 對象轉(zhuǎn)換為請求參數(shù)或響應(yīng)內(nèi)容。
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"));
}
}??注:上述示例代碼,我們并沒有考慮網(wǎng)絡(luò)請求可能失敗的情況。在實(shí)際應(yīng)用中,需要對異常進(jìn)行捕獲和處理。
總結(jié)
以上就是今天要講的內(nèi)容,本文僅僅簡單介紹了 Java 中常見的幾種發(fā)送 HTTP 請求的方式,可以根據(jù)實(shí)際需要選擇合適的方式。
到此這篇關(guān)于Java實(shí)現(xiàn)HTTP請求的4種方式總結(jié)的文章就介紹到這了,更多相關(guān)Java實(shí)現(xiàn)HTTP請求內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java利用EasyExcel實(shí)現(xiàn)導(dǎo)出導(dǎo)入功能的示例代碼
EasyExcel是一個基于Java的、快速、簡潔、解決大文件內(nèi)存溢出的Excel處理工具。本文廢話不多說,直接上手試試,用代碼試試EasyExcel是否真的那么好用2022-11-11
java使用CKEditor實(shí)現(xiàn)圖片上傳功能
這篇文章主要為大家詳細(xì)介紹了java使用CKEditor實(shí)現(xiàn)圖片上傳功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-07-07
SpringBoot中關(guān)于static和templates的注意事項(xiàng)以及webjars的配置
今天小編就為大家分享一篇關(guān)于SpringBoot中關(guān)于static和templates的注意事項(xiàng)以及webjars的配置,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-01-01
java實(shí)現(xiàn)隨機(jī)抽取獎品工具類
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)隨機(jī)抽取獎品工具類,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-05-05
SpringBoot中的@EnableConfigurationProperties注解詳細(xì)解析
這篇文章主要介紹了SpringBoot中的@EnableConfigurationProperties注解詳細(xì)解析,如果一個配置類只配置@ConfigurationProperties注解,而沒有使用@Component或者實(shí)現(xiàn)了@Component的其他注解,那么在IOC容器中是獲取不到properties 配置文件轉(zhuǎn)化的bean,需要的朋友可以參考下2024-01-01

