在Java中通过POST方式发送JSON数据

3
我有这段代码,用于将JSON数据(作为字符串传递)发送到服务器(根据我的测试,当英文字符作为 dataJSON 的值发送时,此代码有效):
private static String sendPost(String url, String dataJSON) throws Exception {

    System.out.println("Data to send: " + dataJSON);


    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    String type = "application/json;charset=utf-8";

    // add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", "Mozilla/5.0");
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
    con.setRequestProperty("Content-Length", String.valueOf(dataJSON.getBytes("UTF-8").length));
    con.setRequestProperty("Content-Type", type);

    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeUTF(dataJSON);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Response Code : " + responseCode);

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

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

    System.out.print("Response string from POST: " + response.toString() + "\n");
    return response.toString();

}

问题是我没有得到正确的响应,例如使用DHC Restlet客户端时获得响应。

问题在于我认为dataJSON必须以UTF8编码。这很可能是服务器期望的方式。 但是,在我尝试转换并发送代码的方式中似乎存在一些问题。 有人能帮我在上面的示例中将数据作为UTF8字符串发送吗?

1个回答

2
我认为我用这种方法解决了问题:
private static String sendPost2(String urlStr, String dataJSON) throws Exception {


    URL url = new URL(urlStr);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setConnectTimeout(5000);
    conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod("POST");

    OutputStream os = conn.getOutputStream();
    os.write(dataJSON.getBytes("UTF-8"));
    os.close();

    // read the response
    InputStream in = new BufferedInputStream(conn.getInputStream());
    String result = new BufferedReader(new InputStreamReader(in)) .lines().collect(Collectors.joining("\n"));

    in.close();
    conn.disconnect();

    return result;

}

如果您发现问题,请建议替代方案。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接