如何使用 apache commons httpclient 和 getmethod 读取 modelandview json 响应?

发布于 2025-01-08 11:35:19 字数 1703 浏览 0 评论 0原文

如果我的格式不对,请原谅(这里是新的)。 我有一个如下所示的 REST 服务(省略了实现细节):

  import org.springframework.stereotype.Controller;
  import org.springframework.web.bind.annotation.RequestMapping;
  import org.springframework.web.bind.annotation.RequestMethod;
  import org.springframework.web.bind.annotation.RequestParam;
  import org.springframework.web.servlet.ModelAndView;
  import org.springframework.web.servlet.view.json.MappingJacksonJsonView;

  @Controller
  @RequestMapping(value={"/myservice", "/myservice/"}, method=RequestMethod.POST)
  public class MyClass{

  @RequestMapping(value={"/",""}, method=RequestMethod.GET)
  public ModelAndView doSomething(@RequestParam(value="params", required=true) String params){

    Map<String,Object> mymap = new HashMap<String,Object>();
    mymap.put("myparam",params);

    return new ModelAndView(new MappingJacksonJsonView(), mymap); 
    }
  }

我想做的是编写一个 HttpClient (使用 org.apache.commons.httpclient.HttpClient,我知道还有另一个来自 apache 的 httpclient)可以获取“来自上述服务的 mymap”对象。我知道我必须在我的客户端代码中执行如下操作:

 public Map<String,String> getMap(){

 HttpClient client = new HttpClient();
 HttpMethod method = new GetMethod("myurl");
 method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
                                  new DefaultHttpMethodRetryHandler(3, false));

 NameValuePair [] pair = { new NameValuePair("content","mytestcontentvalue")};
 ((GetMethod)method).setQueryString(pair);

 int code = client.executeMethod(method);

 Map<String,String> mymap = ??   /// what do i do here?

 return mymap;
}

我一直在寻找解决方案,但我找不到在这里阅读响应的方法。这是我第一次编写客户端和服务,所以可能我找到了解决方案,但从未理解它:( 任何建议都会很有帮助!谢谢。

Please excuse me if my formatting is off (new here).
I have a REST service like below (implementation details omitted):

  import org.springframework.stereotype.Controller;
  import org.springframework.web.bind.annotation.RequestMapping;
  import org.springframework.web.bind.annotation.RequestMethod;
  import org.springframework.web.bind.annotation.RequestParam;
  import org.springframework.web.servlet.ModelAndView;
  import org.springframework.web.servlet.view.json.MappingJacksonJsonView;

  @Controller
  @RequestMapping(value={"/myservice", "/myservice/"}, method=RequestMethod.POST)
  public class MyClass{

  @RequestMapping(value={"/",""}, method=RequestMethod.GET)
  public ModelAndView doSomething(@RequestParam(value="params", required=true) String params){

    Map<String,Object> mymap = new HashMap<String,Object>();
    mymap.put("myparam",params);

    return new ModelAndView(new MappingJacksonJsonView(), mymap); 
    }
  }

What I want to do is write a HttpClient (using org.apache.commons.httpclient.HttpClient, I know there is another httpclient from apache out there) that can GET the "mymap" object from the above service. I understand that I have to do something like below in my client code:

 public Map<String,String> getMap(){

 HttpClient client = new HttpClient();
 HttpMethod method = new GetMethod("myurl");
 method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
                                  new DefaultHttpMethodRetryHandler(3, false));

 NameValuePair [] pair = { new NameValuePair("content","mytestcontentvalue")};
 ((GetMethod)method).setQueryString(pair);

 int code = client.executeMethod(method);

 Map<String,String> mymap = ??   /// what do i do here?

 return mymap;
}

I have been searching for a solution but I can't find a way to read the response here. This is my FIRST time writing a client and service so may be I found a solution but never understood it :(
Any suggestions would really help!!! Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无远思近则忧 2025-01-15 11:35:19

来自 Apache HttpClient 教程

无论服务器返回的状态如何,响应正文始终都会被读取,这一点至关重要。有三种方法可以做到这一点:

  • 调用method.getResponseBody()。这将返回一个字节数组,其中包含响应正文中的数据。
  • 调用method.getResponseBodyAsString()。这将返回一个包含响应正文的字符串。但请注意,从字节到字符串的转换是使用默认编码完成的,因此此方法可能无法跨所有平台移植。
  • 调用 method.getResponseBodyAsStream() 并读取流的全部内容,然后调用 stream.close()。如果可以接收大量数据,则此方法是最好的,因为可以将数据缓冲到文件中或在读取时进行处理。请务必始终读取全部数据并在流上调用 close()

在您以这些方式之一检索响应的内容后,您就可以自由地解析内容并获取您正在寻找的地图...我不相信 Apache HttpClient 为您提供任何更多的解析功能比那个。

您可以使用 Java 的 JSON 库之一(请参阅:json-lib)来解析返回的字符串通过 method.getResponseBodyAsString() 实现,但要注意随着响应大小的增长可能出现的问题。

From the Apache HttpClient tutorial:

It is vital that the response body is always read regardless of the status returned by the server. There are three ways to do this:

  • Call method.getResponseBody(). This will return a byte array containing the data in the response body.
  • Call method.getResponseBodyAsString(). This will return a String containing the response body. Be warned though that the conversion from bytes to a String is done using the default encoding so this method may not be portable across all platforms.
  • Call method.getResponseBodyAsStream() and read the entire contents of the stream then call stream.close(). This method is best if it is possible for a lot of data to be received as it can be buffered to a file or processed as it is read. Be sure to always read the entirety of the data and call close() on the stream.

After you've retrieved the contents of the response in one of these manners, you are then free to parse the contents and get the map you are looking for... I do not believe that Apache HttpClient provides you with any more functionality for parsing than that.

You can use one of the JSON libraries for Java (see: json-lib) to parse the String returned by method.getResponseBodyAsString(), but beware issues that may arise as the size of your response grows.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文