代码之家  ›  专栏  ›  技术社区  ›  Moon

使用HttpURLConnection执行POST请求时获取JSON响应

  •  2
  • Moon  · 技术社区  · 9 年前

    我使用以下代码在REST API上执行POST请求。一切都很顺利。我不能做的是,POST成功后,API在body中返回响应JSON和头,这个JSON有我需要的信息。我无法获得JSON响应。

    我需要这个响应,因为这个响应包括DB生成的ID。我可以在使用firefox的REST客户端插件时看到响应。需要在Java中实现相同的功能。

    enter image description here

        String json = "{\"name\": \"Test by JSON 1\",\"description\": \"Test by JSON 1\",\"fields\": {\"field\": []},\"typeDefinitionId\": \"23\",\"primaryParentId\": \"26982\"}";
        String url = "http://serv23/api/contents";      
        URL obj = new URL(url);
    
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    
        //Setting the Request Method header as POST
        con.setRequestMethod("POST");
    
        //Prepairing credentials
        String cred= "user123:p@ssw0rd";
        byte[] encoded = Base64.encodeBase64(cred.getBytes());           
        String credentials = new String(encoded);
    
        //Setting the Authorization Header as 'Basic' with the given credentials
        con.setRequestProperty  ("Authorization", "Basic " + credentials);
    
        //Setting the Content Type Header as application/json
        con.setRequestProperty("Content-Type", "application/json");
    
        //Overriding the HTTP method as as mentioned in documentation   
        con.setRequestProperty("X-HTTP-Method-Override", "POST");
    
        con.setDoOutput(true);
    
        JSONObject jsonObject = (JSONObject)new JSONParser().parse(json);
    
        OutputStream os = con.getOutputStream();
        os.write(jsonObject.toJSONString().getBytes());
    
        os.flush();
        WriteLine( con.getResponseMessage() );
        int responseCode = con.getResponseCode();
    
    1 回复  |  直到 9 年前
        1
  •  2
  •   Abdul Fatir    9 年前

    String json_response = "";
    InputStreamReader in = new InputStreamReader(con.getInputStream());
    BufferedReader br = new BufferedReader(in);
    String text = "";
    while ((text = br.readLine()) != null) {
      json_response += text;
    }