詳細代碼如下
1 package testproject;
2
3 import java.io.BufferedReader;
4 import java.io.IOException;
5 import java.io.InputStreamReader;
6 import java.io.PrintWriter;
7 import java.net.URL;
8 import java.net.URLConnection;
9 import java.util.List;
10 import java.util.Map;
11 import org.junit.Test;
12 import net.sf.json.JSONObject;
13
14 /**
15 * @author mrjade
16 * @version 建立時間:2017年8月3日
17 * 類說明:GET,POST請求接口測試
18 */
19 public class HttpInterfaceTest {
20 /**
21 * 向指定URL發送GET方法的請求
22 *
23 * @param url
24 * 發送請求的URL
25 * @param param
26 * 請求參數,請求參數應該是name1=value1&name2=value2的形式。
27 * @return URL所代表遠端資源的響應
28 */
29
30 public static String sendGet(String url, String param) {
31 String result = "";
32 BufferedReader in = null;
33 try {
34 String urlName = url + "?" + param;
35 System.out.println("Get請求接口:" + urlName);
36 URL realUrl = new URL(urlName);
37 // 打開和URL之間的連接配接
38 URLConnection conn = realUrl.openConnection();
39 // 設定通用的請求屬性
40 conn.setRequestProperty("accept", "*/*");
41 conn.setRequestProperty("connection", "Keep-Alive");
42 conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
43 // 建立實際的連接配接
44 conn.connect();
45 // 擷取所有響應頭字段
46 Map<String, List<String>> map = conn.getHeaderFields();
47 // 周遊所有的響應頭字段
48 for (String key : map.keySet()) {
49 System.out.println(key + "--->" + map.get(key));
50 }
51 // 定義BufferedReader輸入流來讀取URL的響應
52 in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
53 String line;
54 while ((line = in.readLine()) != null) {
55 result += "\n" + line;
56 }
57 } catch (Exception e) {
58 System.out.println("發送GET請求出現異常!" + e);
59 e.printStackTrace();
60 }
61 // 使用finally塊來關閉輸入流
62 finally {
63 try {
64 if (in != null) {
65 in.close();
66 }
67 } catch (IOException ex) {
68 ex.printStackTrace();
69 }
70 }
71 return result;
72 }
73
74 /**
75 * 向指定URL發送POST方法的請求
76 *
77 * @param url
78 * 發送請求的URL
79 * @param param
80 * 請求參數,請求參數應該是name1=value1&name2=value2的形式或者是json。
81 * @return URL所代表遠端資源的響應
82 */
83 public static String sendPost(String url, String param) {
84 PrintWriter out = null;
85 BufferedReader in = null;
86 String result = "";
87 try {
88 URL realUrl = new URL(url);
89 // 打開和URL之間的連接配接
90 URLConnection conn = realUrl.openConnection();
91 // 設定通用的請求屬性
92 conn.setRequestProperty("accept", "*/*");
93 conn.setRequestProperty("connection", "Keep-Alive");
94 conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
95 conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
96 // 發送POST請求必須設定如下兩行
97 conn.setDoOutput(true);
98 conn.setDoInput(true);
99 // 擷取URLConnection對象對應的輸出流
100 out = new PrintWriter(conn.getOutputStream());
101 // 發送請求參數
102 out.print(param);
103 // flush輸出流的緩沖
104 out.flush();
105 // 定義BufferedReader輸入流來讀取URL的響應
106 in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
107 String line;
108 while ((line = in.readLine()) != null) {
109 result += "\n" + line;
110 }
111 } catch (Exception e) {
112 System.out.println("發送POST請求出現異常!" + e);
113 e.printStackTrace();
114 }
115 // 使用finally塊來關閉輸出流、輸入流
116 finally {
117 try {
118 if (out != null) {
119 out.close();
120 }
121 if (in != null) {
122 in.close();
123 }
124 } catch (IOException ex) {
125 ex.printStackTrace();
126 }
127 }
128 return result;
129 }
130
131 // 調用天氣預報接口請求位址
132 String getUrl = "http://api.ip138.com/weather";
133 // 調用天氣預報接口請求參數
134 String getParams = "&code=350229" + "&callback=find" + "&type=1"
135 + "&token=cc87f3c77747bccbaaee35006da1ebb65e0bad57";
136
137 // 調用天氣預報接口請求參數方式一
138 String postUrl = "http://op.juhe.cn/onebox/weather/query";
139 String postParamsOne = "&cityname=上海市" + "&key=1234567890";
140 // 調用天氣預報接口請求參數方式二
141 String postParamsTwo = "{'cityname':'上海市'," + "'key':'1234567890'}";
142 JSONObject jsonPostParamsTwo = JSONObject.fromObject(postParamsTwo);
143
144 // 提供主方法,測試發送GET請求和POST請求
145 @Test
146 public void test() {
147 // 發送GET請求
148 String getResult = HttpInterfaceTest.sendGet(getUrl, getParams);
149 System.out.println("GET請求參數:" + postParamsOne);
150 System.out.println("GET請求響應結果:" + getResult);
151 // 發送POST請求
152 String postResultOne = HttpInterfaceTest.sendPost(postUrl, postParamsOne);
153 System.out.println("POST請求參數一:" + postParamsOne);
154 System.out.println("POST請求響應結果:" + postResultOne);
155 // 發送POST請求
156 String postResultTwo = HttpInterfaceTest.sendPost(postUrl, jsonPostParamsTwo.toString());
157 System.out.println("POST請求參數二:" + jsonPostParamsTwo);
158 System.out.println("POST請求響應結果:" + postResultTwo);
159 }
160 }
測試結果如下
Change the world by program.
文章轉載請标明出處,如果,您認為閱讀這篇部落格讓您有些收獲,不妨點選一下推薦按鈕,據說喜歡分享的,後來都成了大神
我國每年都有2000萬人得胃炎,胃癌,很大一部分原因是沒有及時吃早餐。
支付寶早餐計劃,每年發放20億早餐補貼來鼓勵您及時吃早餐。打開支付寶首頁搜:510050164,或 點選領取支付寶紅包 領取補貼,用于早餐消費,答應我,好好照顧自己。
歡迎掃碼關注微信公衆号 | 歡迎掃碼加入QQ交流群 | 歡迎掃碼加入微信交流群 |