How to retrieve the array in server side using NanoHTTPD in Android when I post a array var in client side?

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-05 06:32:03

问题


In My.htm, I post a array var mytemp to server side, I hope to retrieve the array var in server side.

I only get the a string D 1,D,2,Tom'Dog if I use the following code, how can I retrieve the array in server side ? Thanks!

BTW, I hope to do a full post, not ajax, so I think that $.ajax() doesn't fit.

My.htm

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

    <script src="js/jquery1.10.2.min.js?isassets=1" type="text/javascript"></script>

    <script type="text/javascript">

     $(function () {
        document.querySelector('#myformID').addEventListener('submit', event => {
           if (!confirm('Do you want to delete selected images?')) {
              event.preventDefault();
           }
        });

        $("#myformID").submit( function(eventObj) {

         var mytemp=new Array();
          mytemp.push("D 1");
          mytemp.push("D,2");
          mytemp.push("Tome'Dog");


           $('<input />').attr('type', 'hidden')
              .attr('name', "myCw")
              .attr('value',mytemp)
             .appendTo('#myformID');
           return true;
        });

     });

    </script>


</head>

<body>
   <div id="container">
       <form action='' method='post' enctype='multipart/form-data' id="myformID">           
           <input type='file' name='myfilename' /> Please select a file
           <input type='submit'name='submit' value='Delete Selecetd Items' />
       </form>

    </div>

</body>
</html>

Server Side

public class HttpServer extends NanoHTTPD {

   private Context mContext;

   public HttpServer(Context myContext) throws IOException {
        super(PublicParFun.GetWebPort(myContext));
        this.mContext=myContext;
        start(NanoHTTPD.SOCKET_READ_TIMEOUT);
   }


    private Response POST(IHTTPSession session) {
         Utility.LogError("Handle Post");

        try {
            Map<String, String> files = new HashMap<String, String>();
            session.parseBody(files);


            Set<String> keys1 =session.getParms().keySet() ;
            for(String key: keys1){
                String name = key;
                String loaction =session.getParms().get(key);                
            }          

        } catch (Exception e) {
            Utility.LogError("This is an error "+e.getMessage() );
            System.out.println("i am error file upload post ");
            e.printStackTrace();
        }
        return newFixedLengthResponse(Response.Status.OK, NanoHTTPD.MIME_PLAINTEXT,"I'm Hello!");
    }




    @Override
    public Response serve(IHTTPSession session) {

        String uri = session.getUri();
        Method method = session.getMethod();

        MURLPar mURLPar=new  MURLPar(mContext);
        FileFolderHelper.SetMURLParValue(mURLPar,session);

        if (mURLPar.isassets.value!=null && mURLPar.isassets.value.equals("1")){
            return GetResponseInputByAssetsFile(uri);
        }


        if (Method.POST.equals(method)) {      
            return POST(session);
        }


        String s=FileFolderHelper.GetStringTemplate(mContext,mContext.getString(R.string.WebImageBase));
        return newFixedLengthResponse(s);
    }
}

To Erfan Mowlaei: Thank you! Is the following code OK?

Client Side:

  var mytemp=new Array();
       mytemp.push("D 1");
       mytemp.push("D, 2");
       mytemp.push("D'3");


       $("#myformID").submit( function(eventObj) {
           $('<input />').attr('type', 'hidden')
              .attr('name', "myCw")
              .attr('value', JSON.stringify(mytemp))
             .appendTo('#myformID');
           return true;
      });

Server Side

 public ArrayList<String> jsonStringToArray(String jsonString) throws JSONException {

        ArrayList<String> stringArray = new ArrayList<String>();

        JSONArray jsonArray = new JSONArray(jsonString);

        for (int i = 0; i < jsonArray.length(); i++) {
            stringArray.add(jsonArray.getString(i));
        }

        return stringArray;
    }

回答1:


I assume what you are getting is either JsonObject or you should send JsonObject in order to be able to get it and convert it to array on server side. if you send the data in JsonArray form, you can get it like this in NanoServer:

@Override
public Response serve(IHTTPSession session) throws JSONException {
    //Log.e("Tag", "request received!");
    Map<String, String> files = new HashMap<String, String>();
    Method method = session.getMethod();
    if (Method.POST.equals(method) || Method.PUT.equals(method)) {
        try {
            session.parseBody(files);
        } catch (IOException ioe) {
            try {
                return new Response(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                Log.e("UnsupportedEncodingException", e.getMessage());
            }
        } catch (ResponseException re) {
            try {
                return new Response(re.getStatus(), MIME_PLAINTEXT, re.getMessage());
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                Log.e("UnsupportedEncodingException", re.getMessage());
            }
        }
    }

    final JSONObject json = new JSONObject(files.get("postData"));
    //Log.e("MyData", json.toString());
    responseInterface.OnResponse(json); // my interface to pass data to other classes
    return newFixedLengthResponse("Success!");
}

Then later in responseInterface.OnResponse(JsonObject json); you can parse that data and make an array out of it.



来源:https://stackoverflow.com/questions/40623211/how-to-retrieve-the-array-in-server-side-using-nanohttpd-in-android-when-i-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!