如何在 java 中构建 RESTful 请求
How to build RESTful request over in java
我试图了解如何向服务器发送 REST 请求。如果我必须使用 httpconnections 或任何其他连接在 java 中将其作为请求来实现,我该怎么做?
POST /resource/1
Host: myownHost
DATE: date
Content-Type: some standard type
这应该如何以标准方式构建?
URL url= new URL("http://myownHost/resource/1");
HttpsURLConnection connect= (HttpsURLConnection) url.openConnection();
connect.setRequestMethod("POST");
connect.setRequestProperty("Host", "myOwnHost");
connect.setRequestProperty("Date","03:14:15 03:14:15 GMT");
connect.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
你应该在这里使用 json
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class NetClientPost {
// http://localhost:8080/RESTfulExample/json/product/post
public static void main(String[] args) {
try {
URL url = new URL("http://myownHost/resource/1");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
String input = "{\"DATE\":\"03:14:15 03:14:15 GMT\",\"host\":\"myownhost\"}";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
浏览更多link
有很多选择,Apache HTTP 客户端 (http://hc.apache.org/httpcomponents-client-4.4.x/index.html) 就是其中之一(并且使事情变得非常简单)
创建 REST 请求可以如此简单(在本例中使用 JSON):
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(
"http://localhost:8080/RESTfulExample/json/product/get");
getRequest.addHeader("accept", "application/json");
HttpResponse response = httpClient.execute(getRequest);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
更新:抱歉,文档的 link 是 updated.Posted 新文档。
有多种方法可以使用 Java 调用 RESTful 服务,但不需要使用原始级别的 API ;-)
它存在一些 RESTful 框架,例如 Restlet 或 JAX-RS。它们针对客户端和服务器端,旨在隐藏此类调用的技术管道。下面是一段代码示例,描述了如何使用 Restlet 和 JSON 解析器进行处理:
JSONObject jsonObj = new JSONObject();
jsonObj.put("host", "...");
ClientResource cr = new Client("http://myownHost/resource/1");
cr.post(new JsonRepresentation(jsonObject);
// In the case of form
// Form form = new Form ();
// form.set("host", "...");
// cr.post(form);
您可以注意到,在前面的代码片段中,headers Content-type
、Date
是根据您发送的内容自动设置的(表单,JSON,. ..)
否则,要添加一个元素,您应该在元素列表资源 (http://myownHost/resources/
) 上使用方法 POST
,或者如果您有唯一标识符,则使用方法 PUT
你想用来识别它 (http://myownHost/resources/1
)。 link 可能对您有用:https://templth.wordpress.com/2014/12/15/designing-a-web-api/.
希望对你有帮助,
蒂埃里
我试图了解如何向服务器发送 REST 请求。如果我必须使用 httpconnections 或任何其他连接在 java 中将其作为请求来实现,我该怎么做?
POST /resource/1
Host: myownHost
DATE: date
Content-Type: some standard type
这应该如何以标准方式构建?
URL url= new URL("http://myownHost/resource/1");
HttpsURLConnection connect= (HttpsURLConnection) url.openConnection();
connect.setRequestMethod("POST");
connect.setRequestProperty("Host", "myOwnHost");
connect.setRequestProperty("Date","03:14:15 03:14:15 GMT");
connect.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
你应该在这里使用 json
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class NetClientPost {
// http://localhost:8080/RESTfulExample/json/product/post
public static void main(String[] args) {
try {
URL url = new URL("http://myownHost/resource/1");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
String input = "{\"DATE\":\"03:14:15 03:14:15 GMT\",\"host\":\"myownhost\"}";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
浏览更多link
有很多选择,Apache HTTP 客户端 (http://hc.apache.org/httpcomponents-client-4.4.x/index.html) 就是其中之一(并且使事情变得非常简单)
创建 REST 请求可以如此简单(在本例中使用 JSON):
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(
"http://localhost:8080/RESTfulExample/json/product/get");
getRequest.addHeader("accept", "application/json");
HttpResponse response = httpClient.execute(getRequest);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
更新:抱歉,文档的 link 是 updated.Posted 新文档。
有多种方法可以使用 Java 调用 RESTful 服务,但不需要使用原始级别的 API ;-)
它存在一些 RESTful 框架,例如 Restlet 或 JAX-RS。它们针对客户端和服务器端,旨在隐藏此类调用的技术管道。下面是一段代码示例,描述了如何使用 Restlet 和 JSON 解析器进行处理:
JSONObject jsonObj = new JSONObject();
jsonObj.put("host", "...");
ClientResource cr = new Client("http://myownHost/resource/1");
cr.post(new JsonRepresentation(jsonObject);
// In the case of form
// Form form = new Form ();
// form.set("host", "...");
// cr.post(form);
您可以注意到,在前面的代码片段中,headers Content-type
、Date
是根据您发送的内容自动设置的(表单,JSON,. ..)
否则,要添加一个元素,您应该在元素列表资源 (http://myownHost/resources/
) 上使用方法 POST
,或者如果您有唯一标识符,则使用方法 PUT
你想用来识别它 (http://myownHost/resources/1
)。 link 可能对您有用:https://templth.wordpress.com/2014/12/15/designing-a-web-api/.
希望对你有帮助, 蒂埃里