通过HttpUrlConnection发送JSON格式的字符串

时间:2018-06-01 21:04:01

标签: java json rest httpurlconnection

我已经做过一些关于使用HttpUrlConnect的研究,我见过的大多数例子都使用过 a)一个params字符串,如下所示:

paramString = "param1=someParam&param2=2ndparam&param3=3rdparam";  

b)使用put方法放置参数:

JSONObject json = new JSONObject();
json.put("param1", "Parameter");
json.put("param2", "Parameter2");
json.put("param3", "Parameter3");

我想发送的格式如下:

{
    "grant_type":"password",
    "username":"testuser@someid.com",
    "password":"testPwd123$"
}

有没有办法让我发送格式化的JSON字符串而不是设置参数或使用参数字符串?我用来发送POST请求的代码如下所示:

public static String PostRequest(String urlString, String token, String jsonString) throws IOException {
    byte[] postData = jsonString.getBytes(StandardCharsets.UTF_8);

    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setInstanceFollowRedirects(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty ("Authorization", "Bearer " + token);
    conn.setUseCaches(false);

    try( DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
        wr.write(postData);
    }

    int responseCode = conn.getResponseCode();
    System.out.println("POST response code: " + responseCode);

    BufferedReader in = new BufferedReader(
            new InputStreamReader(conn.getInputStream()));
    String line;
    StringBuffer response = new StringBuffer();

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

    return response.toString();
}

我愿意接受是否使用不同库的建议,或者是否有任何代码更改,以便采用JSON格式的字符串。

0 个答案:

没有答案