【发布时间】:2014-02-25 02:13:15
【问题描述】:
我正在尝试将一个小字符串从我的应用程序发送到 Java servlet:
//Send user mobile number to the server.
EditText cinMobile = (EditText)findViewById(R.id.mobile_no);
String inputVal = cinMobile.getText().toString();
URL mobileurl = new URL(url);
URLConnection connection = mobileurl.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(inputVal);
out.close();
servlet 应该通过 doPost() 接收值:
//Accept the phone number form the app
int length = request.getContentLength();
byte[] input = new byte[length];
ServletInputStream sin = request.getInputStream();
int c, count = 0;
while((c = sin.read(input, count, input.length-count)) != -1) {
count = +c;
}
sin.close();
String receivedString = new String(input);
response.setStatus(HttpServletResponse.SC_OK);
System.out.print(receivedString);
但是当我运行我的命令并尝试发送字符串时,我在 servlet 端得到了Negative array size exception 的byte[] input = new byte[length]; 行:
Feb 01, 2014 2:06:02 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [project_server.Login] in context with path [/project_server] threw exception
java.lang.NegativeArraySizeException
at project_server.Login.doPost(Login.java:47)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
我不确定这里出了什么问题,但错误意味着它没有收到任何字符串。 LogCat 显示应用程序端没有错误。
【问题讨论】:
-
日志中 request.getContentLength() 的值是多少?
-
@KamleshArya -1;几乎是错误的意思。
标签: java android http jakarta-ee servlets