我是 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/