1.http接口的格式如下:
圖片選擇失敗,我只能把數(shù)據(jù)貼出來(lái),如果有不懂的可以問(wèn)我哈。
http://localhost:8881/department/getDepartmentList接口數(shù)據(jù)如下:(請(qǐng)求方式是GET)
{
"code":0,
"data":[
{"id":1,"departmentName":"軟件研發(fā)部","description":"完成對(duì)項(xiàng)目的功能,性能,接口,界面等方面的編碼工作"},
{"id":2,"departmentName":"軟件技術(shù)部","description":"編寫(xiě)測(cè)試用例,測(cè)試軟件功能,負(fù)責(zé)項(xiàng)目的質(zhì)量審查工作"},
{"id":3,"departmentName":"網(wǎng)絡(luò)管理部","description":"全面掌握網(wǎng)絡(luò)運(yùn)行狀況,及時(shí)報(bào)告網(wǎng)絡(luò)異常情況及其產(chǎn)生原因并做好記錄"},
{"id":4,"departmentName":"市場(chǎng)營(yíng)銷(xiāo)部","description":"配合軟件技術(shù)部收集整理客戶(hù)需求工作中有關(guān)所有事項(xiàng)"},
{"id":5,"departmentName":"行政部門(mén)","description":"主要就是負(fù)責(zé)行政的工作"},
{"id":6,"departmentName":"財(cái)務(wù)部門(mén)","description":"主要就是管錢(qián),記賬"},
{"id":7,"departmentName":"人事部門(mén)","description":"負(fù)責(zé)考情打卡"},
{"id":8,"departmentName":"建庫(kù)部門(mén)","description":"主要負(fù)責(zé)建庫(kù),審核工作"},
{"id":9,"departmentName":"產(chǎn)品部門(mén)","description":"負(fù)責(zé)公司產(chǎn)品推廣"}
]
}
http://localhost:8881/department/getDataById?id=3接口數(shù)據(jù)如下:(請(qǐng)求方式是POST)
{
"code": 0,
"data": {
"id": 3,
"departmentName": "網(wǎng)絡(luò)管理部",
"description": "全面掌握網(wǎng)絡(luò)運(yùn)行狀況,及時(shí)報(bào)告網(wǎng)絡(luò)異常情況及其產(chǎn)生原因并做好記錄"
}
}
2.需要引入的包有:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.42</version>
</dependency>
3.實(shí)現(xiàn)方法如下:文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-538845.html
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public static void main(String[] args) {
//處理json字符串
//testJson();
//動(dòng)態(tài)處理json字符串
//commonHttpMethod("http://localhost:8881/department/getDepartmentList", "", "GET");
//commonHttpMethod("http://localhost:8881/department/getDataById", "id=3", "POST");
}
//測(cè)試
public static void testJson() {
//1、比如前端接收的是str的json字符串,我們是不能直接獲取到名字所對(duì)應(yīng)的值的,所以必須要對(duì)這個(gè)字符串進(jìn)行解析。
String str = "{\"code\":\"0\"," +
"\"message\":\"success\"," +
"\"detail\":[\n" +
" {\"userName\":\"userName\",\n" +
" \"password\":123456,\n" +
" \"phoneNum\":\"13877774534\",\n" +
" \"isAdmin\":1,\n" +
" \"alarms\":[24],\n" +
" \"status\":[1,5,7],\n" +
" \"property\":{}\n" +
" }" +
" ]" +
" }";
//2、先轉(zhuǎn)換成JSONObject類(lèi)型
JSONObject jsonObj = JSON.parseObject(str);
//通過(guò)JSONObject中的getString("key")方法,得到對(duì)應(yīng)的值 {"code":"0","message":"success"}這種類(lèi)型
System.out.println("code:" + jsonObj.getString("code")+" detail:" + jsonObj.getString("detail"));
//3、字符串中含有數(shù)組的,比如像detail中的數(shù)據(jù)
JSONArray jsonInfo = JSONObject.parseArray(jsonObj.getString("detail"));
for (int i = 0; i < jsonInfo.size(); i++) {
JSONObject jsonObject = jsonInfo.getJSONObject(i);
//4、遍歷數(shù)據(jù),存入數(shù)據(jù)庫(kù)【存入數(shù)據(jù)庫(kù)直接調(diào)用增加的方法即可】
String userName = jsonObject.getString("userName");
String password = jsonObject.getString("password");
String phoneNum = jsonObject.getString("phoneNum");
System.out.println("userName:" + userName + " password:" + password + " phoneNum:" + phoneNum);
}
}
public static void commonHttpMethod(String path, String param, String requestMethod) {
if(requestMethod == "POST") { // POST請(qǐng)求
String postData = interfaceUtil(path, param, requestMethod);
JSONObject jsonObj = JSON.parseObject(postData);
//System.out.println("code:"+ jsonObj.getString("code") + " data:"+jsonObj.getString("data"));
//轉(zhuǎn)成對(duì)象 【data為1條數(shù)據(jù)】
JSONObject result = JSONObject.parseObject(JSONObject.toJSONString(jsonObj.get("data")));
System.out.println("result:" + result);
Integer id = result.getInteger("id");
String departmentName = result.getString("departmentName");
String description = result.getString("description");
System.out.println("id:" + id + " departmentName:" + departmentName + " description:" + description);
}else if(requestMethod == "GET") { // GET請(qǐng)求
String getData = interfaceUtil(path, param, requestMethod);
JSONObject jsonObj = JSON.parseObject(getData);
//System.out.println("code:"+ jsonObj.getString("code") + " data:"+jsonObj.getString("data"));
//轉(zhuǎn)成數(shù)組 【data為多條數(shù)據(jù)】
JSONArray json = JSONObject.parseArray(jsonObj.getString("data"));
System.out.println("json:" + json);
for (int i = 0; i < json.size(); i++) {
JSONObject jsonObject = json.getJSONObject(i);
Integer id = jsonObject.getInteger("id");
String departmentName = jsonObject.getString("departmentName");
String description = jsonObject.getString("description");
System.out.println("size:"+json.size() +" id:" + id + " departmentName:" + departmentName + " description:" + description);
}
}
}
/**
* @調(diào)用對(duì)方接口方法 向指定 URL發(fā)送請(qǐng)求,請(qǐng)求參數(shù)為json形式數(shù)據(jù)
* @param path 對(duì)方或第三方提供的路徑
* @param param 向?qū)Ψ交虻谌桨l(fā)送的數(shù)據(jù),大多數(shù)情況下給對(duì)方發(fā)送JSON數(shù)據(jù)讓對(duì)方解析
* @param requestMethod 請(qǐng)求方式 GET POST PUT等
* @return
*/
public static String interfaceUtil(String path, String param, String requestMethod) {
String objectData = "";
try {
URL url = new URL(path);
//打開(kāi)和url之間的連接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
PrintWriter out = null;
//設(shè)置URLConnection的參數(shù)和普通的請(qǐng)求屬性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
if(requestMethod == "POST") {//發(fā)送POST方式的請(qǐng)求,需要獲取URLConnection實(shí)例對(duì)應(yīng)的輸出流來(lái)發(fā)送請(qǐng)求參數(shù)
//設(shè)置是否向httpUrlConnection輸出,設(shè)置是否從httpUrlConnection讀入,發(fā)送post請(qǐng)求必須設(shè)置這兩個(gè)
//最常用的Http請(qǐng)求無(wú)非是get和post,get請(qǐng)求可以獲取靜態(tài)頁(yè)面,也可以把參數(shù)放在URL字串后面,傳遞給servlet,
//post與get的 不同之處在于post的參數(shù)不是放在URL字串里面,而是放在http請(qǐng)求的正文內(nèi)。
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");//GET和POST必須全大寫(xiě)
out = new PrintWriter(connection.getOutputStream());//獲取URLConnection對(duì)象對(duì)應(yīng)的輸出流
out.print(param);//發(fā)送請(qǐng)求參數(shù)即數(shù)據(jù)
out.flush();//緩沖數(shù)據(jù)
}else if(requestMethod == "GET") {//發(fā)送GET方式請(qǐng)求,使用connet方法建立和遠(yuǎn)程資源之間的實(shí)際連接即可
connection.setRequestMethod("GET");//GET和POST必須全大寫(xiě)
connection.connect();
}else {
System.out.println("請(qǐng)重新設(shè)置請(qǐng)求方式!");
}
//獲取URLConnection對(duì)象對(duì)應(yīng)的輸入流
InputStream is = connection.getInputStream();
//構(gòu)造一個(gè)字符流緩存
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String str = "";
while ((str = br.readLine()) != null) {
str = new String(str.getBytes(), "UTF-8");//解決中文亂碼問(wèn)題
System.out.println("str:" + str);
objectData = getStringData(str);
}
//關(guān)閉流
is.close();
//斷開(kāi)連接,最好寫(xiě)上,disconnect是在底層tcp socket鏈接空閑時(shí)才切斷。如果正在被其他線程使用就不切斷。
//固定多線程的話,如果不disconnect,鏈接會(huì)增多,直到收發(fā)不出信息。寫(xiě)上disconnect后正常一些。
connection.disconnect();
System.out.println(requestMethod+"接口調(diào)用完畢!");
} catch (Exception e) {
e.printStackTrace();
}
return objectData;
}
public static String getStringData(String value) {
return value;
}
如果文章有用,麻煩點(diǎn)個(gè)贊,給個(gè)評(píng)論,謝謝。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-538845.html
到了這里,關(guān)于java調(diào)用http接口(get請(qǐng)求和post請(qǐng)求)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!