2013-03-21 60 views
1

我用下面的代碼在我的客戶:如何訪問服務器端的內容?

HttpPost post = new HttpPost(url); 
post.setEntity(new ByteArrayEntity(myString.getBytes("UTF8"))); 
HttpResponse response = this.execute(post); 

我現在想訪問服務器端的字符串。處理方法如下所示:

public void handle(String target, Request baseRequest, HttpServletRequest request, 
HttpServletResponse response) throws IOException, ServletException { ... } 

該請求只允許我訪問內容的長度和類型,而不是內容本身。任何指針?

我使用java作爲一個pl,並從javax.servlet中構建類。

+0

您可能想告訴我們您正在使用什麼樣的(網絡)服務器,以及編程語言/框架。 – 2013-03-21 17:30:56

回答

0

由於某種原因,您已將字符串設置爲唯一的HTTP請求正文,而不是作爲請求參數。所以,爲了獲得它,你需要讀取整個HTTP請求體。這是由

InputStream input = request.getInputStream(); 
// Read it into a String the usual way (using UTF-8). 

請注意,這會返回一個空流可用的Servlet時它已經被事先讀取,例如預先調用getParameter()就可以隱式解析POST請求體。

更理智的方式將其發送作爲一個正常的URL編碼的請求參數如下(酷似作爲默認的HTML表單做)

List<NameValuePair> params = new ArrayList<NameValuePair>(); 
params.add(new BasicNameValuePair("myString", myString)); 
post.setEntity(new UrlEncodedFormEntity(params)); 

,這樣你可以在servlet只是做

String myString = request.getParameter("myString"); 
// ... 
+0

謝謝,解決了我的問題。 – user2196234 2013-03-21 20:01:48