簡體   English   中英

當我在客戶端發布數組變量時,如何使用Android中的NanoHTTPD在服務器端檢索數組?

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

在My.htm中,我將數組var mytemp發布到服務器端,希望在服務器端檢索數組var。

如果使用以下代碼,我只會得到字符串D 1,D,2,Tom'Dog ,如何在服務器端檢索數組? 謝謝!

順便說一句,我希望做一個完整的文章,而不是ajax,所以我認為$ .ajax()不適合。

我的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>

服務器端

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);
    }
}

致Erfan Mowlaei:謝謝! 下列代碼可以嗎?

客戶端:

  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;
      });

服務器端

 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;
    }

我假設您得到的要么是JsonObject,要么應該發送JsonObject以便能夠獲取它並將其轉換為服務器端的數組。 如果以JsonArray形式發送數據,則可以在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!");
}

然后稍后在responseInterface.OnResponse(JsonObject json); 您可以解析該數據並從中創建一個數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM