2012-08-14 67 views
0

我使用servlet和tomcat 6.0創建了一個webservice。我創建了示例Java應用程序來調用Web服務,並且它的工作正常。我需要在調用Web服務時發送一些數據。我在Java應用程序中創建如下如何在servlet中獲取數據?

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格式的數據。
在web服務中,我需要如何獲得這些數據?我在eclispe中檢查了調試模式,我無法找到它。

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

請幫我一把。

回答

2

當你通過郵寄方式將數據發送到一個servlet,該數據是通過輸入流可用。以下是您的發佈方法應該如何。

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中。

+0

感謝Santhosh,它的工作很好..... – Vignesh 2012-08-15 07:05:14

0

這簡單得多。基本上是這樣的:

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(); 
    } 
相關問題