从Java中的HTTP POST请求中读取JSON消息 [英] Read JSON message from HTTP POST request in Java
问题描述
我是Java和客户端服务器编程的新手。
I am new to Java and to client- server programming.
我正在使用嵌入式Jetty,而我正在尝试将JSON字符串发送到某个地址( http:// localhost:7070 / json )然后在该地址中显示JSON字符串。
I am using embedded Jetty, and I'm trying to send a JSON string to some address (http://localhost:7070/json) and then to display the JSON string in that address.
我尝试了以下代码,但我得到的只是null。
I tried the following code but all I get is null.
嵌入式Jetty代码:
Embedded Jetty code:
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的客户端功能:
Client side function for sending the 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函数:
And Servlet functions:
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);
}
}
我从测试类中调用sendHttp()方法,运行嵌入式Jetty服务器代码后(如果这很重要)。
I call the sendHttp() method from a test class, after running the embedded Jetty server code (if that matters).
推荐答案
这是我的代码,这个工作正常
Here is my code this works fine
String data = "";
StringBuilder builder = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
data = builder.toString();
JSONObject object = new JSONObject(data);
//or JSONArray array = new JSONArray(data); which ever the one you want
祝你好运.....
这篇关于从Java中的HTTP POST请求中读取JSON消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!