首页 \ 问答 \ 无法从Jersey GET响应中获取JSON数据(Cannot get JSON data from Jersey GET response)

无法从Jersey GET响应中获取JSON数据(Cannot get JSON data from Jersey GET response)

我正在开发一个宁静的Web客户端,并试图从GET方法的响应中获取JSON有效内容。 我正在使用泽西岛。 但我无法使用response.getEntity()方法读取JSON数据。 我尝试了很多方法,包括response.bufferEntity(),但输出始终保持为空。 下面是我的代码和输出,另外我可以在wireshark中捕获的响应数据包中看到JSON数据。 我真的很感谢每个人都试图帮助找出原因或提供解决方案。 谢谢!

码:

    public JSONObject Get(String requestPath){

    ClientResponse response = webResource.path(requestPath)
            .header("Content-Type", contTypeHeader )
            .header("Accept",acceptHeader)
            .header("Authorization", authZ )
            .get(ClientResponse.class);

    response.bufferEntity();
    if (!(response.getStatus() == 201 || response.getStatus() == 200)) {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
    }

    System.out.println(response.getEntity(JSONObject.class));
    return null;

}

输出总是这样的:{}


I was developing a restful web client and trying to get the JSON payload from the response of a GET method. I am using Jersey. But I just cannot read the JSON data using response.getEntity() method. I tried many methods including response.bufferEntity(), but the output always kept empty. Below is my code and output, and in addition I can see the JSON data right in the response packet captured in wireshark. I would really appreciate everyone trying to help figure out why or provide solution. Thank you!

Code:

    public JSONObject Get(String requestPath){

    ClientResponse response = webResource.path(requestPath)
            .header("Content-Type", contTypeHeader )
            .header("Accept",acceptHeader)
            .header("Authorization", authZ )
            .get(ClientResponse.class);

    response.bufferEntity();
    if (!(response.getStatus() == 201 || response.getStatus() == 200)) {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
    }

    System.out.println(response.getEntity(JSONObject.class));
    return null;

}

and the output is always like this: {}


原文:https://stackoverflow.com/questions/34644676
更新时间:2022-07-15 19:07

最满意答案

当您使用Zend\Mvc\Controller\Plugin\Redirect::toRoute() ,第一个参数是您在module.config.php定义的路由的名称。 例如,您提到的路由被定义为logout

'logout' => array(
    'type' => 'literal',
    'options' => array(
        'route'    => '/logout',
        'defaults' => array(
            '__NAMESPACE__' => 'Users\Controller',
            'controller'    => 'Index',
            'action'        => 'logout',
        ),
    ),
),

因此,要重定向到此路线,请使用以下行。

$this->redirect()->toRoute('logout')

无需将控制器和/或操作作为第二个参数提供,因为您已在路径options中配置了该控制器和/或操作。


When you use the Zend\Mvc\Controller\Plugin\Redirect::toRoute() the first argument is the name of the route you define in module.config.php. For example the route you mentioned is defined as logout.

'logout' => array(
    'type' => 'literal',
    'options' => array(
        'route'    => '/logout',
        'defaults' => array(
            '__NAMESPACE__' => 'Users\Controller',
            'controller'    => 'Index',
            'action'        => 'logout',
        ),
    ),
),

So to redirect to this route use the following line.

$this->redirect()->toRoute('logout')

There is no need to provide the controller and/or action as second argument because you already configured that at the options of the route.

相关问答

更多
  • 你面前有return声明吗? return $this->redirect()->to route('foo/bar'); /编辑:好的,现在我知道你没有,这里有一个解释。 该框架有一个称为短路的概念。 这意味着无论何时在路由或调度期间返回响应,此响应都将立即发送给客户端。 这样做不需要渲染视图脚本等,以加快速度。 Redirect插件创建一个Response对象,其中设置了状态代码(301或302)并注入了Location头。 此位置标头包含您要重定向到的新网址。 如果未在此调用前放置return ,则 ...
  • 如果您要求从当前路线获取这些参数,那么它相当简单: use Zend\Mvc\Controller\AbstractActionController; class Index extends AbstractActionController { public function indexAction() { $controller = $this->params()->fromRoute('controller'); $action = $this->params ...
  • 如果你从ZendSkeletonApplication开始,你是否已经从应用程序模块的配置中删除了预定义的“应用程序”路径 ? 我可以在最新的ZendSkeletonApplication中复制这一点的唯一方法是在已经定义的路由之前定义你的应用程序路由。 例如,module.config.php中的这个路由部分适用于我: 'router' => array( 'routes' => array( 'home' => array( 'type' => 'Zend ...
  • 您指向一个名为'Privado\Controller\Index'但您的invokable称为'Publico\Controller\Index' 。 更改namespace以使其对应。 Privado -> Publico 要么 Publico -> Privado 或为'Privado\Controller\Index'添加控制器 'invokables' => array( 'Privado\Controller\Index' => //your privado controller, ...
  • 在控制器中执行该操作的一些方法是: 使用视图模型 $viewmodel = new ViewModel(); $viewmodel->setVariable('myvar', $myvar); return $viewmodel; 使用layout() $this->layout()->myvar = $myvar; 进入你的视图脚本 myvar; ?> Some ways to do that in your controller: Using view mode ...
  • 通常,您希望通过返回响应来使调度过程短路 。 在route或dispatch期间,您可以返回响应以停止通常的代码流停止并直接完成结果。 如果是ACL检查,很可能您希望尽早返回该响应并重定向到用户的登录页面。 您可以在控制器中构建响应,也可以检查插件的返回值,并在响应时重定向。 请注意,第二种方法与PRG插件的工作方式类似。 第一种方法的一个例子: use Zend\Mvc\Controller\AbstractActionController; class MyController extends Abs ...
  • 好的,我使用全局异常处理程序 儿童控制器
  • 当您使用Zend\Mvc\Controller\Plugin\Redirect::toRoute() ,第一个参数是您在module.config.php定义的路由的名称。 例如,您提到的路由被定义为logout 。 'logout' => array( 'type' => 'literal', 'options' => array( 'route' => '/logout', 'defaults' => array( '__NA ...
  • 这是PRG的一个错误。 它可以处理以下情况: 重定向到URL(没有路由名称,该路由的URL) 重定向到没有参数的路由 重定向到当前匹配的路由 对于第一个场景,您必须传递true作为第二个参数。 // True to keep matched params $url = $this-url()->fromRoute('foo/bar/baz', array(), true); // True to note PRG it's a URL, no route name $prg = $this->prg($ ...
  • 只需将登录过程代码放入登录索引操作中,就不需要为此执行两项操作。 处理完登录后确定失败后,只需将错误消息传递给视图模型并在视图中显示即可。 这可以通过几种方式完成。 $viewModel = new ViewModel(); $viewModel->error_msg = 'Wrong username or password'; return $viewModel; return new ViewModel(array( 'error_msg' => 'Wrong username or pas ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)