使用httpurlconnection发送json数据

时间:2018-09-07 14:11:05

标签: httpurlconnection

我正在尝试使用httpurlconnection发送json数据。但是,在服务器端,parameter(request.getParameter(“ id”))返回null。

我认为,由于httpurlconnection在http-body中发送json数据(也许我已经厌倦了?),所以我将能够从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"));

   }

0 个答案:

没有答案