Java 用HTTP的方式發送JSON報文請求


前言: 

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

需求:

  用HTTP的方式,向URL為127.0.0.1:8888地址發送json報文,返回的結果也是json報文。

 

主要代碼如下:

String resp= null;
            JSONObject obj = new JSONObject();
            obj.put("name", "張三");   
            obj.put("age", "18");   
            String query = obj.toString();
            log.info("發送到URL的報文為:");
            log.info(query);
            try {
                URL url = new URL("http://127.0.0.1:8888"); //url地址

                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");
                connection.setUseCaches(false);
                connection.setInstanceFollowRedirects(true);
                connection.setRequestProperty("Content-Type","application/json");
                connection.connect();

                try (OutputStream os = connection.getOutputStream()) {
                    os.write(query.getBytes("UTF-8"));
                }

                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream()))) {
                    String lines;
                    StringBuffer sbf = new StringBuffer();
                    while ((lines = reader.readLine()) != null) {
                        lines = new String(lines.getBytes(), "utf-8");
                        sbf.append(lines);
                    }
                    log.info("返回來的報文:"+sbf.toString());
                    resp = sbf.toString();    
                   
                }
                connection.disconnect();

            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                JSONObject json = (JSONObject)JSON.parse(resp);
            }

網上還有一種拼json發送報文的方式,也把代碼分享出來:

String resp = null;
String name = request.getParameter("userName");
String age = request.getParameter("userAge");
String query = "{\"name\":\""+name+"\",\"age\":\""+age+"\"}";

try {
                URL url = new URL("http://10.10.10.110:8888"); //url地址

                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");
                connection.setUseCaches(false);
                connection.setInstanceFollowRedirects(true);
                connection.setRequestProperty("Content-Type","application/json");
                connection.connect();

                try (OutputStream os = connection.getOutputStream()) {
                    os.write(query.getBytes("UTF-8"));
                }

                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream()))) {
                    String lines;
                    StringBuffer sbf = new StringBuffer();
                    while ((lines = reader.readLine()) != null) {
                        lines = new String(lines.getBytes(), "utf-8");
                        sbf.append(lines);
                    }
                    log.info("返回來的報文:"+sbf.toString());
                    resp = sbf.toString();    
                   
                }
                connection.disconnect();

            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                JSONObject json = (JSONObject)JSON.parse(resp);
            }

兩種方式其實都是一樣的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM