Java 中的 RESTful 调用 [英] RESTful call in Java

查看:22
本文介绍了Java 中的 RESTful 调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将使用 Java 进行 RESTful 调用.但是,我不知道如何拨打电话.我是否需要使用 URLConnection 或其他?

I am going to make a RESTful call in Java. However, I don't know how to make the call. Do I need to use the URLConnection or others?

推荐答案

如果您从服务提供商(例如 Facebook、Twitter)调用 RESTful 服务,您可以使用任何风格您的选择:

If you are calling a RESTful service from a Service Provider (e.g Facebook, Twitter), you can do it with any flavour of your choice:

如果不想使用外部库,可以使用 java.net.HttpURLConnectionjavax.net.ssl.HttpsURLConnection(对于 SSL),但是这是封装在 java.net.URLConnection 中的工厂类型模式中的调用.要接收结果,您必须connection.getInputStream() 返回一个InputStream.然后,您必须将输入流转换为字符串,并将字符串解析为它的代表对象(例如 XML、JSON 等).

If you don't want to use external libraries, you can use java.net.HttpURLConnection or javax.net.ssl.HttpsURLConnection (for SSL), but that is call encapsulated in a Factory type pattern in java.net.URLConnection. To receive the result, you will have to connection.getInputStream() which returns you an InputStream. You will then have to convert your input stream to string and parse the string into it's representative object (e.g. XML, JSON, etc).

或者,Apache HttpClient(版本 4 是最新的).它比 java 的默认 URLConnection 更稳定和健壮,并且它支持大多数(如果不是全部)HTTP 协议(​​以及它可以设置为严格模式).您的响应仍将在 InputStream 中,您可以按上述方式使用它.

Alternatively, Apache HttpClient (version 4 is the latest). It's more stable and robust than java's default URLConnection and it supports most (if not all) HTTP protocol (as well as it can be set to Strict mode). Your response will still be in InputStream and you can use it as mentioned above.

HttpClient 文档:http://hc.apache.org/httpcomponents-client-ga/tutorial/html/index.html

Documentation on HttpClient: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/index.html

这篇关于Java 中的 RESTful 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆