標籤:reader output his url app 結合 span ams plc
先放一個串連 http://www.techweb.com.cn/network/system/2016-10-11/2407736.shtml
然後貼代碼
public void sendGet(String reqUrl, String params, String contentType) throws Exception { StringBuffer result = new StringBuffer(); BufferedReader reader; URLConnection conn; URL url = new URL(reqUrl); conn = url.openConnection(); conn.setRequestProperty("accept", contentType); conn.setRequestProperty("content-type", contentType); conn.setRequestProperty("connection", "keep-live"); //conn.setRequestProperty("authorization", "Bearer " + this.token); conn.connect(); Map<String, List<String>> map = conn.getHeaderFields(); for (String key : map.keySet()) { System.out.println(key + "--->" + map.get(key)); } reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = reader.readLine()) != null) { result.append(line); } reader.close(); System.err.println(result); }
以上是get方法
public void sendPost(String reqUrl, JSONObject body) throws Exception { StringBuffer result = new StringBuffer(); PrintWriter writer; BufferedReader reader; URLConnection conn; URL url = new URL(reqUrl); conn = url.openConnection(); conn.setRequestProperty("accept", "application/vnd.plcm.plcm-recording-info-list+json"); conn.setRequestProperty("content-type", "application/vnd.plcm.plcm-recording-info-list+json"); conn.setRequestProperty("connection", "keep-alive"); //conn.setRequestProperty("user-agent", // "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0"); conn.setRequestProperty("Authorization", "Bearer " + this.token); conn.setDoOutput(true); conn.setDoInput(true); writer = new PrintWriter(conn.getOutputStream()); if (body != null) { writer.write(body.toString()); } writer.flush(); conn.connect(); Map<String, List<String>> map = conn.getHeaderFields(); for (String key : map.keySet()) { System.out.println(key + "--->" + map.get(key)); } reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = reader.readLine()) != null) { result.append(line); } reader.close(); System.err.println(result.toString()); }
以上是post提交的代碼
(請自動忽略要求標頭裡的accept和content-type)
要說的是,之前在發送get請求時,不小心粘貼了
writer = new PrintWriter(conn.getOutputStream()); if (body != null) { writer.write(body.toString()); } writer.flush();
這部分代碼,服務端拋出了415 作為response code
unsupported media type
結合最開始連結,幾乎可以相信,get只發一次包,而post發兩次,通俗的講,假設把一個httprequest看成是有header和body構成的話,get一次將header和body一併發送,而post先發送header,然後再發送body,
這個有待以後驗證。
java http請求get與post