Java實現(xiàn)HTTP請求的4種方式總結(jié)
前言
在日常工作和學(xué)習(xí)中,有很多地方都需要發(fā)送HTTP請求,本文以Java為例,總結(jié)發(fā)送HTTP請求的多種方式
HTTP請求實現(xiàn)過程
GET??①、創(chuàng)建遠程連接
??②、設(shè)置連接方式(get、post、put…)
??③、設(shè)置連接超時時間
??④、設(shè)置響應(yīng)讀取時間
??⑤、發(fā)起請求
??⑥、獲取請求數(shù)據(jù)
??⑦、關(guān)閉連接
POST??①、創(chuàng)建遠程連接
??②、設(shè)置連接方式(get、post、put。。。)
??③、設(shè)置連接超時時間
??④、設(shè)置響應(yīng)讀取時間
??⑤、當(dāng)向遠程服務(wù)器傳送數(shù)據(jù)/寫數(shù)據(jù)時,需要設(shè)置為true(setDoOutput)
??⑥、當(dāng)前向遠程服務(wù)讀取數(shù)據(jù)時,設(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ò)請求可能失敗的情況。在實際應(yīng)用中,需要對異常進行捕獲和處理。
總結(jié)
以上就是今天要講的內(nèi)容,本文僅僅簡單介紹了 Java 中常見的幾種發(fā)送 HTTP 請求的方式,可以根據(jù)實際需要選擇合適的方式。
到此這篇關(guān)于Java實現(xiàn)HTTP請求的4種方式總結(jié)的文章就介紹到這了,更多相關(guān)Java實現(xiàn)HTTP請求內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解rabbitmq創(chuàng)建queue時arguments參數(shù)注釋
這篇文章主要介紹了rabbitmq創(chuàng)建queue時arguments參數(shù)注釋,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-03-03Spring Cache自定義緩存key和過期時間的實現(xiàn)代碼
使用 Redis的客戶端 Spring Cache時,會發(fā)現(xiàn)生成 key中會多出一個冒號,而且有一個空節(jié)點的存在,查看源碼可知,這是因為 Spring Cache默認(rèn)生成key的策略就是通過兩個冒號來拼接,本文給大家介紹了Spring Cache自定義緩存key和過期時間的實現(xiàn),需要的朋友可以參考下2024-05-05java數(shù)組與以逗號分隔開的字符串的相互轉(zhuǎn)換操作
這篇文章主要介紹了java數(shù)組與以逗號分隔開的字符串的相互轉(zhuǎn)換操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09Spring Data JPA開啟批量更新時樂觀鎖失效問題的解決方法
樂觀鎖的基本思想是,認(rèn)為在大多數(shù)情況下,數(shù)據(jù)訪問不會導(dǎo)致沖突,因此,樂觀鎖允許多個事務(wù)同時讀取和修改相同的數(shù)據(jù),而不進行顯式的鎖定,本文給大家介紹了Spring Data JPA開啟批量更新時樂觀鎖失效問題的解決方法,需要的朋友可以參考下2024-07-07httpclient 請求http數(shù)據(jù),json轉(zhuǎn)map的實例
下面小編就為大家?guī)硪黄猦ttpclient 請求http數(shù)據(jù),json轉(zhuǎn)map的實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-12-12Shiro 控制并發(fā)登錄人數(shù)限制及登錄踢出的實現(xiàn)代碼
本文通過shiro實現(xiàn)一個賬號只能同時一個人使用,本文重點給大家分享Shiro 控制并發(fā)登錄人數(shù)限制及登錄踢出的實現(xiàn)代碼,需要的朋友參考下吧2017-09-09