【问题标题】:How to write JSON into API call using Java HttpURLConnection?如何使用 Java HttpURLConnection 将 JSON 写入 API 调用?
【发布时间】:2011-10-30 08:44:25
【问题描述】:

我需要从一台服务器到另一台服务器进行跨域 API 调用。 基本上我需要发出一个 POST 请求以通过网络发送 Json。我正在使用 Jackson 来处理两个应用程序上的 Json 解析。 下面是我用来执行来自一个域的请求的代码。

URL url = new URL(url); //This is url to POST method of the Servlet on another domain
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
jsonParser.writeValue(connection.getOutputStream(),dto);

当我运行上面的代码发出请求时,另一台服务器上的 doPost() 正确执行(因此 API 调用正在通过)但是 InputStream 中没有任何内容,例如下面的 readLine() 调用返回 null。

BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream( )));
reader.readLine() 

如何使用 HttpUrLConnection 正确发送 Json(我是否缺少配置信息)?另外,我如何从 Servlet 中读取这个 Json 作为这个 API 调用的接收者?(请注意,如上所述,这个 API 调用正在调用另一个域上的 Servlet)

注意:我确实检查了Using java.net.URLConnection to fire and handle HTTP requests,但没有帮助

谢谢!

【问题讨论】:

    标签: java json servlets httpurlconnection


    【解决方案1】:

    我已经检查了 Jackson ObjectMapper 类的 API DOC,方法是 writeValue (here) 在那里,它声明该方法不会显式关闭流,除非您在 JSonFactory 中设置它,或者在您关闭 Mapper 时。

    然后,也许您需要在 OutputStream 上添加显式的 flush() 和 close():

    OutputStream out=connection.getOutputStream();
    try {
        jsonParser.writeValue(out,dto);
        out.flush();
    //catch and handle the exceptions if needed
    } finally {
        out.close();
    }
    

    【讨论】:

    • 当我添加代码以访问响应(检查状态代码)时,请求被执行......奇怪。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-03
    • 1970-01-01
    • 2016-09-10
    • 2015-12-10
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    相关资源
    最近更新 更多