如何从java执行RESTAPI并捕获响应?
在我的浏览器上执行此url: 我不需要登录。它返回以下rest api xml:如何从java执行RESTAPI并捕获响应?,java,xml,rest,Java,Xml,Rest,在我的浏览器上执行此url: 我不需要登录。它返回以下rest api xml: <response> <type>response</type> <ts>1463749194000</ts> <status>OK</status> <msg-version>2.3.0</msg-version> <op>stop</op>
<response>
<type>response</type>
<ts>1463749194000</ts>
<status>OK</status>
<msg-version>2.3.0</msg-version>
<op>stop</op>
<data/>
</response>
响应
1463749194000
好啊
2.3.0
停止
如何从JAVA执行此操作,然后捕获xml响应?正如本文中提到的,这是一个通用的东西,您可以在线找到它 我知道有客户机可以从Java调用REST服务。您的案例中列出了其中两个 案例1:如果您使用的是Jersey REST API。在这里捕获XML,您可以按照自己的方式进行,例如使用JAXB和XML元素来创建JavaBean属性
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);
}
}
}
你做过任何研究吗?这是一个很常见的场景是的,我做到了,你能帮我吗@安德鲁,欢迎你。如果我的答案有助于进行任何必要的编辑,请接受。谢谢