Java 从 android 的 Jersey Resftul webservice 传递和接收 JSON 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20239149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 00:30:04  来源:igfitidea点击:

Pass and receive JSON object from Jersey Resftul webservice from android

javaandroidjsonweb-servicesrest

提问by Mudassir Shahzad

Scenario : Pass username and password in a json object to restful webservice and get a json object in return. Yeah, I know, Its simple but I can't get it work.

场景:将 json 对象中的用户名和密码传递给 restful webservice 并获得一个 json 对象作为回报。是的,我知道,它很简单,但我无法让它工作。

I have been trying to this from several days. So far, I have tried this:

从几天来我一直在尝试这个。到目前为止,我已经尝试过这个:

My restful webservice code

我的宁静网络服务代码

@POST
    @Path("/testJson")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public JSONObject testJson(JSONObject inputJsonObj) throws Exception {

        JSONObject myjson = new JSONObject();

        if(inputJsonObj != null){

        System.out.println("=================================");
        System.out.println("JSON object = " + inputJsonObj.toString());
        System.out.println("=================================");

        }
        else{
            System.out.println("JSON is NULL");

        }

        myjson.put("success", "1");

        System.out.println(myjson.toString());

//        return "string returned";
        return myjson;
    }

And inside my android acivity, the code is

在我的 android 活动中,代码是

// POST request to <service>/SaveVehicle
        HttpPost request = new HttpPost(myURL);
        request.setHeader("Accept", "application/json");
        request.setHeader("Content-type", "application/json");
        request.setHeader("user-agent", "Yoda");


        try {
            // Build JSON string
            // JSONStringer vehicle = new JSONStringer().object()
            // .key("getItInputTO").object().key("zipCode").value("90505")
            // .key("financingOption").value("B").key("make")
            // .value("Scion").key("baseAmountFinanced").value("12000")
            // .key("modelYear").value("2010").key("trimCode")
            // .value("6221").key("totalMSRP").value("15000")
            // .key("aprRate").value("").endObject().endObject();

            JSONObject myjson = new JSONObject();
            myjson.put("1", "first");
            myjson.put("2", "second");

            StringEntity entity = new StringEntity(myjson.toString());
            entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json; charset=utf-8"));

            request.setEntity(entity);

            // Send request to WCF service
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
//          HttpResponse response = httpClient.execute(request, localContext);
            HttpResponse response = httpClient.execute(request);

            resCode = response.getStatusLine().getStatusCode();
            Toast.makeText(getApplicationContext(),
                    response.getStatusLine().getStatusCode() + "",
                    Toast.LENGTH_LONG).show();

            if (resCode == 200) {

                Toast.makeText(getApplicationContext(),
                        response.getStatusLine().getStatusCode() + "",
                        Toast.LENGTH_LONG).show();

                HttpEntity entity2 = (HttpEntity) response.getEntity().getContent();
                String text = getASCIIContentFromEntity(entity);

                if(text!=null){

                    JSONObject obj = new JSONObject(text);

                    lblMsg.setText("Successful!");
                }

                // BufferedReader in = new BufferedReader(new
                // InputStreamReader(response.getEntity().getContent()));
                //
                //
                // String line = "";
                // StringBuffer returnFromServer = new StringBuffer();
                //
                // while ((line = in.readLine()) != null) {
                // returnFromServer.append(line);
                // }
                // // Toast what we got from server
                // Toast.makeText(getApplicationContext(),
                // returnFromServer.toString(), Toast.LENGTH_LONG).show();
                //
                // if (entity != null) {
                // entity.consumeContent();
                // }

            }
        } catch (Exception e) {
            // TODO: handle exception
        }

The commented sections show previous tries.

评论部分显示了以前的尝试。

Output that I get on server console

我在服务器控制台上得到的输出

=================================
JSON object = {}
=================================
{"success":"1"}

My server side receiver json object is not getting populated i don't know why.

我的服务器端接收器 json 对象没有被填充,我不知道为什么。

Note:

笔记:

  1. I have INTERNET and many other permissions in my android manifest.
  2. My webservice is up and running.
  3. I have all the required jars i.e. jersey, json etc
  4. I am using Tomcat 7 for restful webservice
  1. 我的 android 清单中有 INTERNET 和许多其他权限。
  2. 我的网络服务已启动并正在运行。
  3. 我有所有必需的罐子,即球衣、json 等
  4. 我正在使用 Tomcat 7 进行宁静的网络服务

I would highly appreciate any help. Thanks

我将不胜感激任何帮助。谢谢

回答by jean.deanny

I have the same problem as yours. I don't know why, but the temporary solution i am using is creating a class to handle those parameters.

我和你有同样的问题。我不知道为什么,但我使用的临时解决方案是创建一个类来处理这些参数。

That means using Hymanson to convert Json Object <=> "Your Class"

这意味着使用 Hymanson 转换 Json Object <=> "Your Class"

See this tutorial for more information: http://www.mkyong.com/webservices/jax-rs/json-example-with-jersey-Hymanson/

有关更多信息,请参阅本教程:http: //www.mkyong.com/webservices/jax-rs/json-example-with-jersey-Hymanson/

===================================

====================================

And I just found this topic, it may be more useful than the upper solution: Jersey POST Method is receiving null values as parameters

而且我刚发现这个话题,可能比上层的解决方案更有用: Jersey POST Method is received null values as parameters