【问题标题】:Receiving Data on the servlet From Android?在 servlet 上从 Android 接收数据?
【发布时间】:2013-07-30 02:58:54
【问题描述】:

我正在尝试使用 POST 方法将数据从我的 android 应用程序发送到 servlet,但 servlet 不显示任何类型的活动,只是 null 已在输出中显示。尽管我正在使用 GET 方法在 android 应用程序上接收来自 servlet 的响应。 我们尝试在 logcat 上打印操作。它显示数据已发送,但在浏览器上显示为 null。 我也收到异常“单个客户端连接管理器的使用无效:仍然分配连接”

Android 代码:-

String url = "http://10.0.2.2:8084/AndroidApp/AndroidServlet";

DefaultHttpClient httpClient = new DefaultHttpClient();
ResponseHandler<String> res = new BasicResponseHandler();
HttpPost httpPost = new HttpPost(url);

try {

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

nameValuePairs.add(new BasicNameValuePair("Name", name));
nameValuePairs.add(new BasicNameValuePair("Father", father));
nameValuePairs.add(new BasicNameValuePair("Gender", gender));

    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse httpResponse = httpClient.execute(httpPost);
    String response = httpClient.execute(httpPost, res);
}

Servlet 代码:-

public class AndroidServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, ClassNotFoundException, SQLException {

    String Name=request.getParameter("Name");
    String Father=request.getParameter("Father");
    String Gender=request.getParameter("Gender");

     try (PrintWriter out = response.getWriter()) {
        out.println("Hello Android !!!!");
        out.println( Name  + " " +  Father + " "  +  Gender + " ");

    }
}

浏览器输出:-

Hello Android !!!!
null null null

【问题讨论】:

    标签: android eclipse http servlets http-post


    【解决方案1】:

    如果没有外部工具,很难调试网络应用程序,当然如果不编译代码,也很难在代码中找到错误。
    为了调试此类应用程序,我使用 Android Emulator + WireShark 查看 HTTP 请求的正文。希望它会有所帮助。

    编辑:

    ResponseHandler<String> responseHandler = new BasicResponseHandler();
            try{
                String strResponseSaveGoal =
                        httpclient.execute(httppost, responseHandler);
                Log.d("sendCancelOrderRequest", strResponseSaveGoal);
            }catch ( ConnectTimeoutException conEx )
            {
                handler.sendEmptyMessage(CANCEL_REQUEST_ERROR);
            }
            catch (ClientProtocolException ex) {
                Log.d("sendCancelOrderRequest","");
                handler.sendEmptyMessage(CANCEL_REQUEST_ERROR);
            }catch (IOException ex) {
                Log.d("sendCancelOrderRequest","");
                handler.sendEmptyMessage(CANCEL_REQUEST_ERROR);
            }
    

    【讨论】:

    • 那么你能判断我的方法是否有问题,或者方法是正确的,问题在其他地方
    • 我不是 Nastradamus )我无法在我的大脑中调试代码)实际上我在您的代码中看不到任何错误。但我应该建议你捕捉其他异常。看看我上面修改后的答案
    • 设置wireshark。这是查找错误的最佳方法。我无法帮助您,因为我没有 Web 服务器来安装您的应用程序的服务器端。
    猜你喜欢
    • 1970-01-01
    • 2011-09-07
    • 1970-01-01
    • 1970-01-01
    • 2012-03-08
    • 1970-01-01
    • 1970-01-01
    • 2021-05-25
    • 1970-01-01
    相关资源
    最近更新 更多