服务器响应请求时代码不起作用

时间:2016-12-25 11:36:28

标签: android json server

最近我正在学习服务器和android之间的请求和响应。 我尝试在服务器响应时更新JSON文件,但我失败了。更新代码不起作用。

像这样的服务器代码:代码“JSONArray”不起作用但我不知道为什么。

public class AndroidServerServlet extends HttpServlet {

    private static final long serialVersionUID = 6792396567928634227L;

    public void doPost(HttpServletRequest request, 
        HttpServletResponse response)throws ServletException, IOException {
        response.setContentType("text/plain; charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        String username = request.getParameter("username");
        String newPassword = request.getParameter("newpassword");
        PrintWriter printWriter = response.getWriter();
        printWriter.print("hello android, password changed");
        printWriter.flush();
        printWriter.close();
        System.out.println(username+"\n"+newPassword);
        ChangePassword(username , newPassword);
        }
        private void ChangePassword(String username , String password){
            try {
                InputStream in = AndroidServerServlet.class
                    .getClassLoader().getResourceAsStream("/1.json");

                Scanner scanner = new Scanner(in, "UTF-8");  //InputStream → String
                String jsonData = scanner.useDelimiter("\\A").next();
                System.out.println(jsonData);
                scanner.close();
                JSONArray jsonArray = new JSONArray(jsonData);
                for(int i = 0;i < jsonArray.length(); i++){
                    JSONObject object = jsonArray.getJSONObject(i);
                    if(username.equals(object.getString("username")))
                        object.put("password",password);
                }
                System.out.println(jsonData);
                in.close();
            }catch (Exception e){
                System.out.print("Exception\n");
                }
            }
        }
像这样的android代码:( surbmit是一个按钮)

 surbmit.setOnClickListener(new View.OnClickListener() {
            @Override
                public void onClick(View v) {
                    RequestParams requestParams = new RequestParams();
                    requestParams.add("newpassword", "newpassword");
                    requestParams.add("username","test1");
                    new AsyncHttpClient().post("http://10.0.2.2:8080/AndroidServerServlet", requestParams, new AsyncHttpResponseHandler() {
                        @Override
                        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                            if(statusCode == 200){
                                Toast.makeText(MainActivity.this, new String(responseBody), Toast.LENGTH_LONG).show();
                            }
                        }
                        @Override
                        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                            Toast.makeText(MainActivity.this, "server doesn't response", Toast.LENGTH_LONG).show();
                        }
                    });
                }
            });

并且json文件是这样的:

[{"username":"test1","password":"password1"},
{"username":"test2","password":"password2"},
{"username":"test3","password":"password3"}]

当我调试服务器代码时,我发现了一个错误:java.long.NoClassDefFoundError:org / json / JSONArray.but我有alerady在项目中添加jar,为什么错误出现?

BTW:我使用IntelliJ IDEA + MAVEN + Tomcat来构建我的服务器。

错误报告:

 java.lang.NoClassDefFoundError: org/json/JSONArray
at AndroidServerServlet.ChangePassword(AndroidServerServlet.java:41)
at AndroidServerServlet.doPost(AndroidServerServlet.java:31)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:789)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1437)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

我试图删除我添加的jar,错误的报告仍然与top相同,证明我没有真正添加jar,但我该如何添加呢?

1 个答案:

答案 0 :(得分:0)

我建议使用HttpUrlConnection而不是ServletRequest / Response,Scanner等...

请检查此链接:https://developer.android.com/reference/java/net/HttpURLConnection.html

您可以在发布内容部分找到一个示例。