Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用JavaSpring';s RestTemplate';什么是交换方法?_Java_Spring_Http_Resttemplate - Fatal编程技术网

如何使用JavaSpring';s RestTemplate';什么是交换方法?

如何使用JavaSpring';s RestTemplate';什么是交换方法?,java,spring,http,resttemplate,Java,Spring,Http,Resttemplate,我正在尝试使用RestTemplate的exchange方法发送HTTP请求。但是,由于某些原因,发送请求的HTTP正文似乎是空的 以下是我目前拥有的代码(原始代码更复杂): package-somepackage; 导入org.springframework.http.HttpEntity; 导入org.springframework.http.HttpHeaders; 导入org.springframework.http.HttpMethod; 导入org.springframework.w

我正在尝试使用RestTemplate的
exchange
方法发送HTTP请求。但是,由于某些原因,发送请求的HTTP正文似乎是空的

以下是我目前拥有的代码(原始代码更复杂):

package-somepackage;
导入org.springframework.http.HttpEntity;
导入org.springframework.http.HttpHeaders;
导入org.springframework.http.HttpMethod;
导入org.springframework.web.client.rest模板;
公共类{
公共静态void main(字符串[]args){
HttpEntity实体=新的HttpEntity(“正文内容”,新的HttpHeaders());
新建RestTemplate().exchange(“http://localhost:5678/someRequest,HttpMethod.GET,entity,String.class);
}
}
为了确认上面的代码是否有效,我在终端中运行了
nc-l 5678
(侦听端口5678上的请求),并在IDE中运行了上面的代码。我的终端中的
nc
命令打印出一个没有正文的HTTP请求(我希望它有一个带有字符串“body contents”的正文)

为什么这样不行?我怎样才能修好它

注意:以下是使我决定使用
exchange
方法的需求

  • 它必须是一个GET请求
  • 请求需要有一个主体
  • 我必须设置一些标题
  • 我需要阅读回复的正文

GET
方法没有主体。您可能需要将
HttpMethod.GET
更改为
HttpMethod.POST

如果要在
GET
中提供参数,可以将URL更改为类似
http://localhost:5678/someRequest?expiry=23000

更多详细信息参见。

HTTP服务器可以选择忽略GET请求的主体。请看,您是否可以尝试详细说明为什么您认为应该使用
GET
请求并包含正文?也许有更好的方法来解决您的问题。@junvar我正在实现的REST服务提供AWS S3预签名URL。(它们是动态生成的URL,会在一段时间后过期。)我使用这些URL下载静态文件(或者至少是通常静态的文件)(因此使用GET方法)。我需要将过期时间作为一个参数传递(因此是正文),我不确定是否需要其他参数(我可能稍后会进行一些身份验证)。我的REST服务中的所有其他内容都使用JSON参数,如果有一个东西使用了其他东西,那就太奇怪了。不确定这是否是最好的方法,但您可以在url中添加过期时间,如
http://localhost:5678/someRequest?expiry=23000
@Kartik我想我会照你说的做。
package somepackage;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.web.client.RestTemplate;

public class SomeMainClass {
    public static void main(String[] args) {
        HttpEntity<String> entity = new HttpEntity<>("body contents", new HttpHeaders());
        new RestTemplate().exchange("http://localhost:5678/someRequest", HttpMethod.GET, entity, String.class);
    }
}