繁体   English   中英

如何在servlet中获取数据?

[英]How to Get Data in servlet?

我使用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格式的数据。
在webservice中我如何获取这些数据? 我在eclispe中检查了调试模式,我无法找到它。

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

请帮帮我。

当您通过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

这更简单。 基本上看起来像这样:

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();
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM