java - 从 Java 中的 HTTP POST 请求中读取 JSON 消息

标签 java json http-post embedded-jetty

我是 Java 和客户端-服务器编程的新手。

我正在使用嵌入式 Jetty,我正在尝试将 JSON 字符串发送到某个地址 ( http://localhost:7070/json ),然后在该地址中显示 JSON 字符串。

我尝试了以下代码,但我得到的都是空值。

嵌入式 jetty 代码:

public static void main(String[] args) throws Exception {
    Server server = new Server(7070);
    ServletContextHandler handler = new ServletContextHandler(server, "/json");
    handler.addServlet(ExampleServlet.class, "/");
    server.start();
}

用于发送 Http POST 的客户端函数:

public static void sendHttp(){
    HttpClient httpClient = HttpClientBuilder.create().build(); //Use this instead 

    try {
        HttpPost request = new HttpPost("http://localhost:7070/json");

        JSONObject object = new JSONObject();
        try {
            object.put("name", "MyName");
            object.put("age", "26");
        } catch (Exception ex) {
            System.out.println("Error: " + ex.getMessage());
        }

        String message = object.toString();
        request.setEntity(new StringEntity(message, "UTF8"));
        request.setHeader("Content-type", "application/json");

        HttpResponse response = httpClient.execute(request);

        // handle response here...
    }catch (Exception ex) {
        // handle exception here
    } finally {
    }
}

和 Servlet 函数:

public class ExampleServlet extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        //System.out.println("test get\n");
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        //System.out.println("test post\n");
        PrintWriter out = resp.getWriter();
        String json_str = req.getParameter("name");
        out.print(json_str);
    }
}

在运行嵌入式 Jetty 服务器代码(如果重要的话)之后,我从测试类调用 sendHttp() 方法。

最佳答案

要从 Post 请求中获取数据,您需要获取内容。试试这个:

String data = IOUtils.toString(req.getInputStream(), "UTF-8");

关于java - 从 Java 中的 HTTP POST 请求中读取 JSON 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33896136/

相关文章:

javascript - 获取发送到 Python/Django 的 POST 请求的 None 值(通过 Axios 库)

android - 使用多部分数据发布将文本数据与图像一起发送到服务器

java - IntelliJ IDEA 创建的 JAR 文件不运行

php - 当我使用 httpPost 从 android 设备调用它时,我的 php 代码出错

Java 删除变音符号

javascript - Google Dart 添加元素到 DropDown

javascript - 将 Jquery 数据发布到 Express

ios - 从 MySQL 数据库导入 iOS 应用程序中的数据

java - GXT - 窗口中的截断文本

java - 如何从媒体播放器创建音频文件