【问题标题】:How to Get Data in servlet?如何在 servlet 中获取数据?
【发布时间】:2012-08-10 16:36:29
【问题描述】:

我使用 servlet 和 tomcat 6.0 创建了一个 web 服务。我创建了示例 java 应用程序来调用 Web 服务并且它工作正常。我需要在调用 Web 服务时发送一些数据。我在java应用程序中创建如下

StringEntity zStringEntityL = new StringEntity(zAPIInputStringP.toString());
zStringEntityL.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
        "application/json"));
HttpParams aHttpParamsL = new BasicHttpParams();
HttpProtocolParams.setVersion(aHttpParamsL, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(aHttpParamsL, HTTP.UTF_8);

SchemeRegistry aSchemeRegistryL = new SchemeRegistry();
aSchemeRegistryL.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

ClientConnectionManager ccm = new ThreadSafeClientConnManager(aHttpParamsL, aSchemeRegistryL);
DefaultHttpClient client = new DefaultHttpClient(ccm, aHttpParamsL);
HttpPost aHttpPostL = new HttpPost(URL + zAPIName);
aHttpPostL.setHeader("Authorization", "Basic");



aHttpPostL.setEntity(zStringEntityL);
HttpResponse aHttpResponseL;
aHttpResponseL = client.execute(aHttpPostL); 

这里的“zAPIInputStringP”是我的 JSON 格式数据。
在网络服务中,我需要如何获取这些数据?我在 eclispe 中检查了调试模式,我无法找到它。

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{
    //How to get data?
}

请帮帮我。

【问题讨论】:

    标签: java web-services http servlets


    【解决方案1】:

    当您通过 post 方法将数据发送到 servlet 时,数据可通过 输入流 获得。以下是您的 post 方法的外观。

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    String zAPIInputStringP = "";
    
    BufferedReader in = new BufferedReader(new InputStreamReader(
                    request.getInputStream()));
    String line = in.readLine();
    while (line != null) {
        zAPIInputStringP += line;
        line = in.readLine();
    }
    
    
    }
    

    您的 JSON 字符串包含在 zAPIInputStringP 中。

    【讨论】:

      【解决方案2】:

      这要简单得多。基本上看起来像这样:

      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
          {
            response.setContentType("application/json");
          // Get the printwriter object from response to write the required json object to the output stream      
          PrintWriter out = response.getWriter();
          // Assuming your json object is **zStringEntityL**, perform the following, it will return your json object  
          StringEntity zStringEntityL = new StringEntity(zAPIInputStringP.toString());
          out.print(zStringEntityL);
          out.flush();
          }
      

      【讨论】:

        猜你喜欢
        • 2023-03-20
        • 2012-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-29
        相关资源
        最近更新 更多