通过Java中的POST发送JSON数据

时间:2017-02-09 12:54:41

标签: java jackson

我有这个代码将JSON数据(作为字符串传递)发送到服务器(在我测试的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(); } 中,当英文字符作为值发送时,此代码有效):

dataJSON

问题是我得不到正确的答案,例如我使用DHC Restlet Client。

问题是我认为List<Game>必须以UTF8编码。这就是服务器最有可能的期望。 但似乎我在代码中遇到了一些问题,就像我尝试转换它并发送它一样。 有人可以帮助我在上面的例子中以UTF8字符串的身份发送数据吗?

1 个答案:

答案 0 :(得分: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;

}

如果您发现问题,请提出建议。