客戶端POST發送json數據給服務端,客戶端端接收服務器端json數據響應

客戶端POST發送json數據給服務端

//請求的地址
        String url = "http://localhost:8080/springmvc/request/postRequest";
        //創建Http Request(內部使用HttpURLConnection)
        ClientHttpRequest request = 
            new SimpleClientHttpRequestFactory().   
                createRequest(new URI(url), HttpMethod.POST);
        //設置請求頭的內容類型頭和內容編碼(GBK)
        request.getHeaders().set("Content-Type", "application/json;charset=gbk");
        //以GBK編碼寫出請求內容體
        String jsonData = "{\"username\":\"admin\", \"password\":\"admin\"}";
        request.getBody().write(jsonData.getBytes("gbk"));
        //發送請求並得到響應
        ClientHttpResponse response = request.execute();
        System.out.println(response.getStatusCode());


客戶端接收服務器端json數據響應

  public static void jsonRequest() throws IOException, URISyntaxException {
        //請求的地址
        String url = "http://localhost:8080/springmvc/response/reponseContent";
        //創建Http Request(內部使用HttpURLConnection)
        ClientHttpRequest request = 
            new SimpleClientHttpRequestFactory().   
                createRequest(new URI(url), HttpMethod.POST);
        //設置客戶端可接受的媒體類型
        request.getHeaders().set("Accept", "application/json");        
        //發送請求並得到響應
        ClientHttpResponse response = request.execute();
        //得到響應體的編碼方式
        Charset charset = response.getHeaders().getContentType().getCharSet();        
        //得到響應體的內容        
        InputStream is = response.getBody();
        byte bytes[] = new byte[(int)response.getHeaders().getContentLength()];
        is.read(bytes);
        String jsonData = new String(bytes, charset);
        System.out.println("charset : " + charset + ", json data : " + jsonData);
        }

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