Я пытаюсь использовать httpurlconnection для отправки данных JSON. Но на стороне сервера параметр (request.getParameter ("id") возвращает ноль.
Я думал, что так как httpurlconnection отправляет данные json в http-body (может быть, я беспокоюсь?), Я смогу получить параметры из httpservletrequest.
Как я могу решить эту проблему? Я включил мой код ниже:
Клиентская сторона
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true);
String id = request.getParameter("id");
String pwd = request.getParameter("pwd");
StringBuffer sb = new StringBuffer();
JSONObject obj = new JSONObject();
obj.put("id", id);
obj.put("pwd", pwd);
URL url = new URL("http://localhost:8080/RESTful_Back/rest/LogicService/login");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset","utf-8");
conn.setReadTimeout(20000);
conn.setConnectTimeout(20000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
OutputStream os = null;
try {
os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(obj.toString());
writer.flush();
writer.close();
os.close();
}
catch(Exception e) {
e.printStackTrace();
}
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while((line = in.readLine()) != null) {
sb.append(line);
}
in.close();
System.out.println(sb.toString());
conn.disconnect();
Серверная сторона
@Path("/LogicService")
public class LogicService {
@POST
@Path("/login")
public void loginMethod(@Context HttpServletRequest request, @Context HttpServletResponse response) throws IOException {
System.out.println("PARAM ID = "+request.getParameter("id"));
}