【问题标题】:Java HttpClient: Not able to read json data in the post requestJava HttpClient:无法在发布请求中读取 json 数据
【发布时间】:2013-02-16 12:40:26
【问题描述】:

这里我使用 HttpClient 发布 JSON 数据。但我无法读取其他应用程序上的数据。当我执行 request.getParameter("username") 时,它返回 null。我的两个应用程序都部署在同一台服务器上。请告诉我我做错了什么。谢谢

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        DefaultHttpClient httpClient = new DefaultHttpClient();

        HttpPost postRequest = new HttpPost("http://localhost:8080/AuthenticationService/UserIdentificationServlet");
        postRequest.setHeader("Content-type", "application/json");

        StringEntity input = new StringEntity("{\"username\":\""+username+"\"}");
        input.setContentType("application/json");
        postRequest.setEntity(input);

        HttpResponse postResponse = httpClient.execute(postRequest);

        BufferedReader br = new BufferedReader(new InputStreamReader((postResponse.getEntity().getContent())));
        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

        httpClient.getConnectionManager().shutdown();
    }

【问题讨论】:

  • 您需要了解application/x-www-form-urlencoded 即表单请求参数(HttpServletRequest#getParameter()) 与application/json 之间的区别,后者的请求正文为json (HttpServletRequest#getInputStream())。

标签: java apache-httpclient-4.x


【解决方案1】:

如果你想使用request.getParameter,那么你必须以URL编码格式发布数据。

//this example from apache httpcomponents doc
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("param1", "value1"));
formparams.add(new BasicNameValuePair("param2", "value2"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
HttpPost httppost = new HttpPost("http://localhost/handler.do");
httppost.setEntity(entity);

【讨论】:

    猜你喜欢
    • 2013-03-03
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 2018-09-18
    • 1970-01-01
    • 2011-11-27
    • 2014-09-08
    相关资源
    最近更新 更多