[英]httpPost request from Android to java server (jetty): parameters get lost?
我正在按照這個 howto發送一個相當簡單的 httpPost 請求。 (它是德語,但您可以查看 HTTP POST 示例)。 這就是我得到的:
HttpPost httpPost = new HttpPost(params[0]);
HttpParams httpParams = new BasicHttpParams();
httpParams.setParameter("title", "message");
//... setting some other parameters like http timeout, which I checked and which work
httpPost.setParams(httpParams);
//HttpEntity myEntity = new StringEntity(messageBody);
//httpPost.setEntity(myEntity);
response = httpClient.execute(httpPost);
(評論部分也是我嘗試過的,但沒有結果)。
服務器代碼如下所示:
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
response.setContentType("text/plain;charset=utf-8");
if (target.contentEquals("/postKdm"))
{
String title = request.getParameter("title");
InputStream instream = request.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line);
}
System.out.println(title);
response.setStatus(HttpServletResponse.SC_OK);
}
}
其中 String 標題和 InputStream 均為空/空。 我已經調試並檢查了請求 object,但找不到任何看起來像我的參數的東西。
另外,我在這里發現了一些聽起來與我的問題相似的東西,但答案對我沒有多大幫助,因為我不使用 Apache Camel,因此不能使用 Exchange class。
哦,類似的 GET 請求運行良好,但在這里我卡住了。 :/
我將不勝感激任何幫助!
親切的問候,水母
我仍然不知道為什么“setParams”不起作用。 但是我使用 Wireshark 來檢查我的傳出請求,之后我找到了使用 HttpEntity 的解決方案(就像上面評論的部分一樣):
HttpEntity myEntity = new StringEntity(message);
httpPost.setEntity(myEntity);
response = httpClient.execute(httpPost);
由於克里斯的回答,我發現了服務器端,只是我當然用字符緩沖區替換了字節緩沖區,如下所示:
private String getInputString() throws IOException
{
InputStream is = request.getInputStream();
if (is != null)
{
Writer writer = new StringWriter();
char[] buffer = new char[request.getContentLength()];
try
{
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1)
{
writer.write(buffer, 0, n);
}
}
finally
{
is.close();
}
return writer.toString();
}
else
{
return "";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.