前言:
項目調用第三方接口時,通常是用socket或者http的通訊方式發送請求:http 為短連接,客戶端發送請求都需要服務器端回送響應,請求結束后,主動釋放鏈接。Socket為長連接:通常情況下Socket 連接就是 TCP 連接,因此 Socket 連接一旦建立,通訊雙方開始互發數據內容,直到雙方斷開連接。下面介紹HTTP的方式發送和接收JSON報文。
需求:
用HTTP的方式,向URL為10.10.10.110:8888地址發送json報文,返回的結果也是json報文。

主要代碼如下:
1 String resp= null; 2 JSONObject obj = new JSONObject(); 3 obj.put("name", "張三"); 4 obj.put("age", "18"); 5 String query = obj.toString(); 6 log.info("發送到URL的報文為:"); 7 log.info(query); 8 try { 9 URL url = new URL("http://10.10.10.110:8888"); //url地址 10 11 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 12 connection.setDoInput(true); 13 connection.setDoOutput(true); 14 connection.setRequestMethod("POST"); 15 connection.setUseCaches(false); 16 connection.setInstanceFollowRedirects(true); 17 connection.setRequestProperty("Content-Type","application/json"); 18 connection.connect(); 19 20 try (OutputStream os = connection.getOutputStream()) { 21 os.write(query.getBytes("UTF-8")); 22 } 23 24 try (BufferedReader reader = new BufferedReader( 25 new InputStreamReader(connection.getInputStream()))) { 26 String lines; 27 StringBuffer sbf = new StringBuffer(); 28 while ((lines = reader.readLine()) != null) { 29 lines = new String(lines.getBytes(), "utf-8"); 30 sbf.append(lines); 31 } 32 log.info("返回來的報文:"+sbf.toString()); 33 resp = sbf.toString(); 34 35 } 36 connection.disconnect(); 37 38 } catch (Exception e) { 39 e.printStackTrace(); 40 }finally{ 41 JSONObject json = (JSONObject)JSON.parse(resp); 42 }
網上還有一種拼json發送報文的方式,也把代碼分享出來:
1 String resp = null; 2 String name = request.getParameter("userName"); 3 String age = request.getParameter("userAge"); 4 String query = "{\"name\":\""+name+"\",\"age\":\""+age+"\"}"; 5 6 try { 7 URL url = new URL("http://10.10.10.110:8888"); //url地址 8 9 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 10 connection.setDoInput(true); 11 connection.setDoOutput(true); 12 connection.setRequestMethod("POST"); 13 connection.setUseCaches(false); 14 connection.setInstanceFollowRedirects(true); 15 connection.setRequestProperty("Content-Type","application/json"); 16 connection.connect(); 17 18 try (OutputStream os = connection.getOutputStream()) { 19 os.write(query.getBytes("UTF-8")); 20 } 21 22 try (BufferedReader reader = new BufferedReader( 23 new InputStreamReader(connection.getInputStream()))) { 24 String lines; 25 StringBuffer sbf = new StringBuffer(); 26 while ((lines = reader.readLine()) != null) { 27 lines = new String(lines.getBytes(), "utf-8"); 28 sbf.append(lines); 29 } 30 log.info("返回來的報文:"+sbf.toString()); 31 resp = sbf.toString(); 32 33 } 34 connection.disconnect(); 35 36 } catch (Exception e) { 37 e.printStackTrace(); 38 }finally{ 39 JSONObject json = (JSONObject)JSON.parse(resp); 40 }
兩種方式其實都是一樣的。寫得不對的地方,往各位擼過的大拿指正~
