【问题标题】:How to get data from response如何从响应中获取数据
【发布时间】:2015-02-13 13:48:45
【问题描述】:

我创建了 2 个网络服务,并且能够发送一些数据。

使用这三行代码

HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("http://localhost/<appln-folder-name>/method/domethod?data1=abc&data2=xyz");
HttpResponse response = client.execute(request);

在这种情况下,我发布的方法将 2 数据发送到 Web 服务器。

@Path("/domethod")
    // Produces JSON as response
    @Produces(MediaType.APPLICATION_JSON) 
    // Query parameters are parameters: http://localhost/<appln-folder-name>/method/domethod?data1=abc&data2=xyz
    public String doLogin(@QueryParam("data1") String d1, @QueryParam("data2") String d2){
        String response = "";
        System.out.println("Data: d1="+d1+"; d2="+d2);
        if(checkData(d1, d1)){
            response = Utitlity.constructJSON("tag",true);
        }else{
            response = Utitlity.constructJSON("tag", false, "Error");
        }
    return response;        
    }

System.out 正常工作并打印:d1=abc; d2=xyz 但是现在应用程序无法返回对第一种方法的响应。 我怎样才能得到响应?

【问题讨论】:

  • 这取决于您如何编写 Web 服务。您需要向我们展示您是如何编写它的,以及您是如何尝试返回数据的。
  • 完成!这里是第二个代码
  • 您返回的是纯字符串?你期待的 json 是什么?
  • 好吧,在 Android 中我以这种方式获取值: JSONObject obj = new JSONObject(response);通过这种方式,我有 obj 具有正确的结果。在 JAVA JSONObject 中不允许将响应作为参数。我该怎么做?
  • 嘿,我回复了...我认为您应该只返回一个 Response 类的实例。它将转换为 json。记得创建公共的 getter 和 setter!

标签: java database web-services request response


【解决方案1】:

您已经在此处收到回复:

HttpResponse response = client.execute(request);

由于您已经在使用org.apache.httpcomponents,您可以执行以下操作:

String result = EntityUtils.toString(response.getEntity());

之后,您将数据作为字符串,只需按照您的意愿使用它。

编辑: 更多信息,您的数据位于响应的实体中,即HttpEntity 对象。您可以从那里以InputStream 的形式获取内容并按照您的意愿阅读,我的示例是一个简单的字符串。

【讨论】:

    【解决方案2】:

    首先,我将使用 get 方法进行注释。然后我会使用 Java 类并让库为我将类转换为 json。

    尝试这样做:

    @GET
    @Path("/domethod")
        // Produces JSON as response
        @Produces(MediaType.APPLICATION_JSON) 
        // Query parameters are parameters: http://localhost/<appln-folder-name>/method/domethod?data1=abc&data2=xyz
        public String doLogin(@QueryParam("data1") String d1, @QueryParam("data2") String d2){
            Response response = new Response();
            System.out.println("Data: d1="+d1+"; d2="+d2);
            if(checkData(d1, d1)){
                //set in response the tag property to true and maybe another property to OK
                response.setTag(true);
                response.setStatus("OK");
            }else{
                 //set in response the tag property to false and maybe another property to ERROR
                response.setTag(false);
                response.setStatus("ERROR");
            }
        return response;        
        }
    

    【讨论】:

      猜你喜欢
      • 2021-11-15
      • 1970-01-01
      • 2019-09-17
      • 2011-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-22
      相关资源
      最近更新 更多