Java發(fā)送http請(qǐng)求的示例(get與post方法請(qǐng)求)
package com.jiucool.www.struts.action; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; public class post_request { public static final String GET_URL = "http://www.cngolon.com/request.action?key=j0r56u2"; public static final String POST_URL = "http://www.cngolon.com/request.action"; //get()請(qǐng)求 public static void readContentFromGet() throws IOException { // 拼湊get請(qǐng)求的URL字串,使用URLEncoder.encode對(duì)特殊和不可見(jiàn)字符進(jìn)行編碼 String getURL = GET_URL + "&activatecode=" + URLEncoder.encode("中國(guó)聚龍", "utf-8"); URL getUrl = new URL(getURL); // 根據(jù)拼湊的URL,打開(kāi)連接,URL.openConnection函數(shù)會(huì)根據(jù)URL的類型, // 返回不同的URLConnection子類的對(duì)象,這里URL是一個(gè)http,因此實(shí)際返回的是HttpURLConnection HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection(); // 進(jìn)行連接,但是實(shí)際上get request要在下一句的connection.getInputStream()函數(shù)中才會(huì)真正發(fā)到 // 服務(wù)器 connection.connect(); // 取得輸入流,并使用Reader讀取 BufferedReader reader = new BufferedReader( new InputStreamReader(connection.getInputStream(), "utf-8") ); //設(shè)置編碼,否則中文亂碼 System.out.println("============================="); System.out.println("Contents of get request"); System.out.println("============================="); String lines; while ((lines = reader.readLine()) != null) { //lines = new String(lines.getBytes(), "utf-8"); System.out.println(lines); } reader.close(); // 斷開(kāi)連接 connection.disconnect(); System.out.println("============================="); System.out.println("Contents of get request ends"); System.out.println("============================="); } //post()請(qǐng)求 public static void readContentFromPost() throws IOException { // Post請(qǐng)求的url,與get不同的是不需要帶參數(shù) URL postUrl = new URL(POST_URL); // 打開(kāi)連接 HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection(); // Output to the connection. Default is // false, set to true because post // method must write something to the // connection // 設(shè)置是否向connection輸出,因?yàn)檫@個(gè)是post請(qǐng)求,參數(shù)要放在 // http正文內(nèi),因此需要設(shè)為true connection.setDoOutput(true); // Read from the connection. Default is true. connection.setDoInput(true); // Set the post method. Default is GET connection.setRequestMethod("POST"); // Post cannot use caches // Post 請(qǐng)求不能使用緩存 connection.setUseCaches(false); // This method takes effects to // every instances of this class. // URLConnection.setFollowRedirects是static函數(shù),作用于所有的URLConnection對(duì)象。 // connection.setFollowRedirects(true); // This methods only // takes effacts to this // instance. // URLConnection.setInstanceFollowRedirects是成員函數(shù),僅作用于當(dāng)前函數(shù) connection.setInstanceFollowRedirects(true); // Set the content type to urlencoded, // because we will write // some URL-encoded content to the // connection. Settings above must be set before connect! // 配置本次連接的Content-type,配置為application/x-www-form-urlencoded的 // 意思是正文是urlencoded編碼過(guò)的form參數(shù),下面我們可以看到我們對(duì)正文內(nèi)容使用URLEncoder.encode // 進(jìn)行編碼 connection.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded" ); // 連接,從postUrl.openConnection()至此的配置必須要在connect之前完成, // 要注意的是connection.getOutputStream會(huì)隱含的進(jìn)行connect。 connection.connect(); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); // The URL-encoded contend // 正文,正文內(nèi)容其實(shí)跟get的URL中'?'后的參數(shù)字符串一致 String content = "key=j0r53nmbbd78x7m1pqml06u2&type=1&toemail=cngolon@gmail.com" + "&activatecode=" + URLEncoder.encode("中國(guó)聚龍", "utf-8"); // DataOutputStream.writeBytes將字符串中的16位的unicode字符以8位的字符形式寫(xiě)道流里面 out.writeBytes(content); out.flush(); out.close(); // flush and close BufferedReader reader = new BufferedReader( new InputStreamReader(connection.getInputStream(), "utf-8") ); //設(shè)置編碼,否則中文亂碼 String line = ""; System.out.println("============================="); System.out.println("Contents of post request"); System.out.println("============================="); while ((line = reader.readLine()) != null) { //line = new String(line.getBytes(), "utf-8"); System.out.println(line); } System.out.println("============================="); System.out.println("Contents of post request ends"); System.out.println("============================="); reader.close(); connection.disconnect(); } }
HttpURLConnection.connect函數(shù),實(shí)際上只是建立了一個(gè)與服務(wù)器的tcp連接,并沒(méi)有實(shí)際發(fā)送http請(qǐng)求。無(wú)論是post還是get,http請(qǐng)求實(shí)際上直到HttpURLConnection.getInputStream()這個(gè)函數(shù)里面才正式發(fā)送出去。
在readContentFromPost()中,順序是重中之重,對(duì)connection對(duì)象的一切配置(那一堆set函數(shù))都必須要在connect()函數(shù)執(zhí)行之前完成。而對(duì)outputStream的寫(xiě)操作,又必須要在inputStream的讀操作之前。這些順序?qū)嶋H上是由http請(qǐng)求的格式?jīng)Q定的。
http請(qǐng)求實(shí)際上由兩部分組成,一個(gè)是http頭,所有關(guān)于此次http請(qǐng)求的配置都在http頭里面定義,一個(gè)是正文content,在connect()函數(shù)里面,會(huì)根據(jù)HttpURLConnection對(duì)象的配置值生成http頭,因此在調(diào)用connect函數(shù)之前,就必須把所有的配置準(zhǔn)備好。
緊接著http頭的是http請(qǐng)求的正文,正文的內(nèi)容通過(guò)outputStream寫(xiě)入,實(shí)際上outputStream不是一個(gè)網(wǎng)絡(luò)流,充其量是個(gè)字符串流,往里面寫(xiě)入的東西不會(huì)立即發(fā)送到網(wǎng)絡(luò),而是在流關(guān)閉后,根據(jù)輸入的內(nèi)容生成http正文。
至此,http請(qǐng)求的東西已經(jīng)準(zhǔn)備就緒。在getInputStream()函數(shù)調(diào)用的時(shí)候,就會(huì)把準(zhǔn)備好的http請(qǐng)求正式發(fā)送到服務(wù)器了,然后返回一個(gè)輸入流,用于讀取服務(wù)器對(duì)于此次http請(qǐng)求的返回信息。由于http請(qǐng)求在getInputStream的時(shí)候已經(jīng)發(fā)送出去了(包括http頭和正文),因此在getInputStream()函數(shù)之后對(duì)connection對(duì)象進(jìn)行設(shè)置(對(duì)http頭的信息進(jìn)行修改)或者寫(xiě)入outputStream(對(duì)正文進(jìn)行修改)都是沒(méi)有意義的了,執(zhí)行這些操作會(huì)導(dǎo)致異常的發(fā)生。
以上就是Java發(fā)送http請(qǐng)求的示例(get與post方法請(qǐng)求)的詳細(xì)內(nèi)容,更多關(guān)于Java發(fā)送http請(qǐng)求的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Spring Boot整合Mybatis并完成CRUD操作的實(shí)現(xiàn)示例
這篇文章主要介紹了Spring Boot整合Mybatis并完成CRUD操作的實(shí)現(xiàn)示例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-12-12SpringBoot查詢PGSQL分表后的數(shù)據(jù)的代碼示例
數(shù)據(jù)庫(kù)用的pgsql,在表數(shù)據(jù)超過(guò)100w條的時(shí)候執(zhí)行定時(shí)任務(wù)進(jìn)行了分表,分表后表名命名為原的表名后面拼接時(shí)間,但是我在java業(yè)務(wù)代碼中,我想查詢之前的那條數(shù)據(jù)就查不到了,本文給大家介紹了SpringBoot中如何查詢PGSQL分表后的數(shù)據(jù),需要的朋友可以參考下2024-05-05Spring中的spring-retry重試機(jī)制解析
這篇文章主要介紹了Spring中的spring-retry重試機(jī)制解析,spring-retry可以通過(guò)注解,在不入侵原有業(yè)務(wù)邏輯代碼的方式下,優(yōu)雅的實(shí)現(xiàn)重處理功能,在spring-retry中,所有配置都是基于簡(jiǎn)單注釋的,需要的朋友可以參考下2024-01-01SpringBoot項(xiàng)目使用內(nèi)置的單機(jī)任務(wù)調(diào)度功能詳解
這篇文章主要介紹了SpringBoot項(xiàng)目使用內(nèi)置的單機(jī)任務(wù)調(diào)度功能詳解,SpringBoot框架中提供了2個(gè)注解來(lái)讓開(kāi)發(fā)者快速配置來(lái)實(shí)現(xiàn)單機(jī)定時(shí)任務(wù)調(diào)度的功能,分別是@EnableScheduling和 @Scheduled,需要的朋友可以參考下2024-01-01Jersey Restful接口如何獲取參數(shù)的問(wèn)題
這篇文章主要介紹了Jersey Restful接口如何獲取參數(shù)的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06