Я новичок в Java и программировании на клиент-сервер.Чтение сообщения JSON из запроса HTTP POST в Java
Я использую встроенный Jetty, и я пытаюсь отправить строку JSON на какой-то адрес (http://localhost:7070/json), а затем отобразить строку JSON в этом адресе.
Я пробовал следующий код, но все, что я получаю, равно null.
Встроенный код 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);
}
}
я вызываю метод sendHttp() из тестовый класс после запуска встроенного кода сервера Jetty (если это имеет значение).
Может быть, вы должны смотреть на: http://stackoverflow.com/questions/11901831/how- to-get-json-object-from-http-request-in-java – guuspor