JAVA HTTP POST參數爲一個對象或數組

原文鏈接http://zhaochao.net/index.php/2015/12/04/4/

問題描述

最近接到一個很簡單的問題,對方提供了一個接口,讓我每隔一段時間像他的接口推送一些數據,因爲數據量比較大,所以這種Http 請求類型肯定是Post請求。這種推送過去的參數是一個很大的數組,而且數據字段比較多,所以用key=value 這種形式傳過去就不太適合了,應該直接將這種數組加入Http的body體中,一次性傳過去,接收放也不需要一個一個字段解析,全部取出body體中數據,再解析就可以了。
假設傳遞參數爲

[
    {
        "name": "趙雲",
        "age": "20"
    },
    {
        "name": "馬超",
        "age": "30"
    }
]

服務端實現

新建一個serlvet3.0 處理Post 請求

@WebServlet("/hello")
public class Hello extends HttpServlet {
    private static final long serialVersionUID = 1L;  
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        BufferedReader br=new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
        String line="";
        String res="";
        while(null!=(line=br.readLine())){
            res+=line;
        }
        JSONArray array=JSONArray.parseArray(res);
        for(int i=0;i<array.size();i++){
            JSONObject user=array.getJSONObject(i);
            System.out.println(String.format("name=%s age=%s",user.getString("name"),user.getString("age")));
        }
        response.setCharacterEncoding("utf-8");
        response.getWriter().append("Served at: ").append(res);

    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

客戶端調用實現

public class Main { 
    public static final String ADD_URL = "http://localhost:8080/PostDemo/hello"; 
    public static void main(String[] args) { 
         try { 
             //創建連接 
             URL url = new URL(ADD_URL); 
             HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
             connection.setDoOutput(true); 
             connection.setDoInput(true); 
             connection.setRequestMethod("POST"); 
             connection.setUseCaches(false); 
             connection.setInstanceFollowRedirects(true); 
             connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); 
             connection.connect(); 
             //POST請求 
             DataOutputStream out = new DataOutputStream(connection.getOutputStream()); 
             JSONObject user = new JSONObject(); 
             user.put("name", "趙雲"); 
             user.put("age", "20");
             JSONObject user2 = new JSONObject(); 
             user2.put("name","馬超"); 
             user2.put("age", "30");
             JSONArray userArray=new JSONArray();
             userArray.add(user);
             userArray.add(user2);
             out.write(userArray.toString().getBytes("UTF-8"));
             out.flush(); 
             out.close(); 
             //讀取響應 
             BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
             String lines; 
             StringBuffer sb = new StringBuffer(""); 
             while ((lines = reader.readLine()) != null) { 
                 lines = new String(lines.getBytes(), "utf-8"); 
                 sb.append(lines); 
             } 
             System.out.println(sb); 
             reader.close(); 
             // 斷開連接 
             connection.disconnect(); 
         } catch (MalformedURLException e) { 
             // TODO Auto-generated catch block 
             e.printStackTrace(); 
         } catch (UnsupportedEncodingException e) { 
             // TODO Auto-generated catch block 
             e.printStackTrace(); 
         } catch (IOException e) { 
             // TODO Auto-generated catch block 
             e.printStackTrace(); 
         } 
    } 
} 

測試結果

服務端輸出結果
服務端結果
客戶端輸出結果
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章