从HttpURLConnection对象

时间:2019-05-24 07:22:14

标签: java json

我要点击一个网址以得到回复{"status":"true", "message":"Success"}。我需要获取唯一的值true作为字符串作为此方法的返回类型。我在网站服务过程中使用的是Jersey Jackson。

这是我的代码

private void sendingPostRequest() throws Exception {

    String url = "http:localhost:8080/RestPractice/rest/UserService/path";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();


    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);

    Gson gsonObj = new Gson();
    Map<String, String> inputMap = new HashMap<String, String>();
    inputMap.put("name", "somename");


    String jsonStr = gsonObj.toJson(inputMap);
    System.out.println(jsonStr);


    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(jsonStr);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String output;
    StringBuffer response = new StringBuffer();

    while ((output = in.readLine()) != null) {
        response.append(output);
    }
    in.close();


    System.out.println(response.toString());
}

0 个答案:

没有答案