【问题标题】:get JSON response while performing POST request with HttpURLConnection使用 HttpURLConnection 执行 POST 请求时获取 JSON 响应
【发布时间】:2016-06-27 05:23:42
【问题描述】:

我正在使用以下代码在 REST API 上执行 POST 请求。一切正常。我无法做的是在 POST 成功后,API 在正文中返回带有标题的响应 JSON,这个 JSON 包含我需要的信息。我无法获得 JSON 响应。

我需要此响应,因为此响应包含 DB 生成的 ID。我可以在使用 firefox 的 REST Client 插件时看到响应。需要在 Java 中实现相同的功能。

    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();

【问题讨论】:

    标签: java json httpurlconnection


    【解决方案1】:

    获取输入流并读取它。

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

    【讨论】:

    • 刷新输出流后?
    • @Moon 是的,os.flush();,然后是os.close();。之后阅读我在回答中提到的回复。
    • BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream()) ); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close();我正在使用这个,有点变化
    猜你喜欢
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多