Java如何發起http請求
- 前言
- 一、GET與POST
- 1.GET方法
- 2.POST方法
- 實作代碼
- 實體演示
- 字串轉json
- 結束
前言
在未來做專案中,一些功能模塊可能會采用不同的語言進行撰寫,這就需要http請求進行模塊的呼叫,那么下面,我將以Java為例,詳細說明如何發起http請求,
一、GET與POST
GET和POST是HTTP的兩個常用方法,
GET指從指定的服務器中獲取資料
POST指提交資料給指定的服務器處理
1.GET方法
使用GET方法,需要傳遞的引數被附加在URL地址后面一起發送到服務器,
例如:http://121.41.111.94/submit?name=zxy&age=21
特點:
- GET請求能夠被快取
- GET請求會保存在瀏覽器的瀏覽記錄中
- 以GET請求的URL能夠保存為瀏覽器書簽
- GET請求有長度限制
- GET請求主要用以獲取資料
2.POST方法
使用POST方法,需要傳遞的引數在POST資訊中單獨存在,和HTTP請求一起發送到服務器,
例如:
POST /submit HTTP/1.1
Host 121.41.111.94
name=zxy&age=21
特點:
- POST請求不能被快取下來
- POST請求不會保存在瀏覽器瀏覽記錄中
- 以POST請求的URL無法保存為瀏覽器書簽
- POST請求沒有長度限制
實作代碼
下面將Java發送GET/POST請求封裝成HttpRequest類,可以直接使用,HttpRequest類代碼如下:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
public class HttpRequest {
/**
* 向指定URL發送GET方法的請求
*
* @param url
* 發送請求的URL
* @param param
* 請求引數,請求引數應該是 name1=value1&name2=value2 的形式,
* @return URL 所代表遠程資源的回應結果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打開和URL之間的連接
URLConnection connection = realUrl.openConnection();
// 設定通用的請求屬性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立實際的連接
connection.connect();
// 獲取所有回應頭欄位
Map<String, List<String>> map = connection.getHeaderFields();
// 遍歷所有的回應頭欄位
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定義 BufferedReader輸入流來讀取URL的回應
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("發送GET請求出現例外!" + e);
e.printStackTrace();
}
// 使用finally塊來關閉輸入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 發送POST方法的請求
*
* @param url
* 發送請求的 URL
* @param param
* 請求引數,請求引數應該是 name1=value1&name2=value2 的形式,
* @return 所代表遠程資源的回應結果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打開和URL之間的連接
URLConnection conn = realUrl.openConnection();
// 設定通用的請求屬性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 發送POST請求必須設定如下兩行
conn.setDoOutput(true);
conn.setDoInput(true);
// 獲取URLConnection物件對應的輸出流
out = new PrintWriter(conn.getOutputStream());
// 發送請求引數
out.print(param);
// flush輸出流的緩沖
out.flush();
// 定義BufferedReader輸入流來讀取URL的回應
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("發送 POST 請求出現例外!"+e);
e.printStackTrace();
}
//使用finally塊來關閉輸出流、輸入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
}
實體演示
在搭建flask框架文章中,我們已經寫好了一個功能模塊show(). 該功能模塊如下:
#app的路由地址"/show"即為ajax中定義的url地址,采用POST、GET方法均可提交
@app.route("/show",methods=["GET", "POST"])
def show():
#首先獲取前端傳入的name資料
if request.method == "POST":
name = request.form.get("name")
if request.method == "GET":
name = request.args.get("name")
#創建Database類的物件sql,test為需要訪問的資料庫名字 具體可見Database類的建構式
sql = Database("test")
try:
#執行sql陳述句 多說一句,f+字串的形式,可以在字串里面以{}的形式加入變數名 結果保存在result陣列中
result = sql.execute(f"SELECT type FROM type WHERE name='{name}'")
except Exception as e:
return {'status':"error", 'message': "code error"}
else:
if not len(result) == 0:
#這個result,我覺得也可以把它當成資料表,查詢的結果至多一個,result[0][0]回傳陣列中的第一行第一列
return {'status':'success','message':result[0][0]}
else:
return "rbq"
下面 我們利用POST方法發起請求,Java代碼如下:
//創建發起http請求物件
HttpRequest h = new HttpRequest();
//向121.41.111.94/show發起POST請求,并傳入name引數
String content = h.sendPost("http://121.41.111.94/show","name=張新宇");
System.out.println(content);
我們列印出content值,發現就是python中show()回傳的json(在Java中,content被識別為String型別,而不是json)

(在轉換程序中,不知道出什么問題了,中文顯示了unicode編碼,但在后面的轉json格式后就沒有這樣的問題了)
字串轉json
Java成功發起Http請求后,由于回傳值是String型別,而不是原本python函式中的json格式,所以我們需要將字串型別轉為json格式,并通過鍵值對的形式得出message對應的值,
首先在maven中引入jar包:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
轉換代碼如下:
import com.alibaba.fastjson.JSONObject;
JSONObject jsonObject = JSONObject.parseObject(content);
System.out.println(jsonObject);
System.out.println(jsonObject.getString("message"));
運行結果:

結束
以上就是Java發起http請求,從而呼叫由python撰寫的功能模塊,在使用python撰寫功能模塊時,可以回傳json格式的資料,在之后使用Java進行呼叫時,使用工具進行轉換得出需要的資料,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/262543.html
標籤:java
