当前位置 : 主页 > 手机开发 > android >

如何从android传递参数到RESTlet webservice?

来源:互联网 收集:自由互联 发布时间:2021-06-11
我一直在网上寻找如何将参数传递给RESTlet webservice,但似乎没有太多关于RESTlet的教程. 我想从我的Android应用程序中的表单发送一些参数(如果我可以使用JSON这样做会很棒). 我解决了这个问
我一直在网上寻找如何将参数传递给RESTlet webservice,但似乎没有太多关于RESTlet的教程.

我想从我的Android应用程序中的表单发送一些参数(如果我可以使用JSON这样做会很棒).

我解决了这个问题

至于服务器端

@Post
public JSONArray serverSideFunction(Representation entity)
throws JSONException {

    try {
        JSONObject req = (new JsonRepresentation(entity)).getJsonObject();
        System.out.println(req.getString(/* filed name */));
        System.out.println(req.getString(/* filed name */));
        /* 
         * you can retrieve all the fields here 
         * and make all necessary actions
         */
    } catch (IOException e) {
        e.printStackTrace();
    }
}

至于Android Side

HttpClient client = new DefaultHttpClient();
    String responseBody;
    JSONObject jsonObject = new JSONObject();

    try{
        HttpPost post = new HttpPost(WebService_URL);
        jsonObject.put("field1", ".........");
        jsonObject.put("field2", ".........");

        StringEntity se = new StringEntity(jsonObject.toString());  

        post.setEntity(se);
        post.setHeader(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        post.setHeader("Content-type", "application/json");
        Log.e("webservice request","executing");

        ResponseHandler responseHandler = new BasicResponseHandler();
        responseBody = client.execute(post, responseHandler);
        /* 
         * You can work here on your responseBody
         * if it's a simple String or XML/JSON response
         */
    }
    catch (Exception e) {
        e.printStackTrace();
    }

我希望这可能有所帮助

网友评论