【问题标题】:How to execute rest api from java and capture the response?如何从java执行rest api并捕获响应?
【发布时间】:2023-03-04 14:25:01
【问题描述】:

在我的浏览器上执行这个网址:http://localhost:3161/devices/simulator/stop

我不需要登录。它返回这个 api xml:

<response>
    <type>response</type>
    <ts>1463749194000</ts>
    <status>OK</status>
    <msg-version>2.3.0</msg-version>
    <op>stop</op>
    <data/>
</response>

如何从 JAVA 执行此操作,然后捕获 xml 响应?

【问题讨论】:

  • 你做过任何研究吗?这是一个很常见的场景
  • 是的,我做到了,你能帮帮我吗? @andrew.butkus

标签: java xml rest


【解决方案1】:

正如这篇文章中提到的,它是通用的东西,你已经可以在网上找到它了..

我知道有客户端可以从 Java 调用 REST 服务。您的案例中列出了其中两个。

case -1 :如果您使用的是 Jersey REST API。这里要捕获 XML,你可以按照自己的方式进行,例如使用 JAXB 和 XML 元素来获取 Java Bean 属性。

import java.io.IOException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import org.apache.http.client.ClientProtocolException;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
public class Test {
 public static void main(String[] args) throws ClientProtocolException, IOException {
  ClientConfig config = new DefaultClientConfig();
  Client client = Client.create(config);
  WebResource service = client.resource(UriBuilder.fromUri('http://localhost:3161/devices/simulator/stop').build());
  // getting XML data
  System.out.println(service. path('restPath').path('resourcePath').accept(MediaType.APPLICATION_JSON).get(String.class));
  // getting JSON data
  System.out.println(service. path('restPath').path('resourcePath').accept(MediaType.APPLICATION_XML).get(String.class));
 }
}

案例 2:使用 HTTP 方法,是一种简单的方法,但是在这里解析 XML 而不是打印出来

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class Test {
 public static void main(String[] args) throws ClientProtocolException, IOException {
  HttpClient client = new DefaultHttpClient();
  HttpGet request = new HttpGet('http://localhost:3161/devices/simulator/stop');
  HttpResponse response = client.execute(request);
  BufferedReader rd = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
  String line = '';
  while ((line = rd.readLine()) != null) {
    System.out.println(line);
  }
 }
}

【讨论】:

  • 欢迎您。如果需要,请接受我的回答,如果它有助于任何编辑。谢谢
猜你喜欢
  • 2021-01-21
  • 1970-01-01
  • 2016-09-12
  • 1970-01-01
  • 1970-01-01
  • 2015-10-28
  • 1970-01-01
  • 2018-11-25
  • 1970-01-01
相关资源
最近更新 更多