gpt4 book ai didi

java - 如何在 Java 中构建 RESTful 请求

转载 作者:可可西里 更新时间:2023-11-01 16:33:18 26 4
gpt4 key购买 nike

我试图了解如何向服务器发送 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");

最佳答案

有很多选项,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())));

更新:抱歉,文档链接已更新。发布了新链接。

关于java - 如何在 Java 中构建 RESTful 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29064436/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com