标签: resttemplate

Spring RESTTemplate的泛型

我有一个这样的课:

public class Wrapper<T> {

 private String message;
 private T data;

 public String getMessage() {
    return message;
 }

 public void setMessage(String message) {
    this.message = message;
 }

 public T getData() {
    return data;
 }

 public void setData(T data) {
    this.data = data;
 }

}
Run Code Online (Sandbox Code Playgroud)

我使用resttemplate如下:

...
Wrapper<Model> response = restTemplate.getForObject(URL, Wrapper.class, myMap);
Model model = response.getData();
...
Run Code Online (Sandbox Code Playgroud)

然而它抛出一个:

ClassCastException
Run Code Online (Sandbox Code Playgroud)

我读到了:尝试在java中使用Jackson但没有帮助的问题.有一些与我的问题相关的主题等:https://jira.springsource.org/browse/SPR-7002https://jira.springsource.org/browse/SPR-7023

有任何想法吗?

PS:我的错误是:

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to a.b.c.d.Model
Run Code Online (Sandbox Code Playgroud)

我认为resttemplate不能理解我的泛型变量,也许它接受它作为Object而不是泛型T.所以它变成了LinkedHashMap.你可以在这里阅读它说当从它的组合解释时: …

java generics spring jackson resttemplate

59
推荐指数
2
解决办法
5万
查看次数

使用Spring RestTemplate for Android进行经过身份验证的POST请求

我有一个RESTful API,我试图通过Android和RestTemplate连接.所有对API的请求都通过HTTP身份验证进行身份验证,方法是设置HttpEntity的标头,然后使用RestTemplate的exchange()方法.

所有GET请求都以这种方式工作,但我无法弄清楚如何完成经过身份验证的POST请求.postForObjectpostForEntity处理POST,但没有简单的方法来设置身份验证标头.

因此对于GET来说,这很有用:

HttpAuthentication httpAuthentication = new HttpBasicAuthentication("username", "password");
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAuthorization(httpAuthentication);

HttpEntity<?> httpEntity = new HttpEntity<Object>(requestHeaders);

MyModel[] models = restTemplate.exchange("/api/url", HttpMethod.GET, httpEntity, MyModel[].class);
Run Code Online (Sandbox Code Playgroud)

但POST显然无法使用,exchange()因为它从不发送自定义标头,我也看不到如何设置请求体使用exchange().

从RestTemplate进行经过身份验证的POST请求的最简单方法是什么?

java rest spring android resttemplate

58
推荐指数
4
解决办法
18万
查看次数

在Spring RestTemplate中禁用SSL证书验证

我在两台不同的机器上有两个基于Spring的Web应用程序A和B.

我想从Web应用程序A到Web应用程序B进行https调用,但是我在机器B中使用自签名证书.因此我的HTTPS请求失败.

如何在Spring中使用RestTemplate时禁用https证书验证?我想禁用验证,因为Web应用A和B都在内部网络中,但数据传输必须通过HTTPS进行

validation spring ssl-certificate resttemplate

54
推荐指数
8
解决办法
9万
查看次数

在泛型参数的泛型方法中使用Spring RestTemplate

要使用Spring RestTemplate的泛型类型,我们需要使用ParameterizedTypeReference(无法获得通用的ResponseEntity <T>,其中T是泛型类"SomeClass <SomeGenericType>")

假设我有一些课

public class MyClass {
    int users[];

    public int[] getUsers() { return users; }
    public void setUsers(int[] users) {this.users = users;}
}
Run Code Online (Sandbox Code Playgroud)

还有一些包装类

public class ResponseWrapper <T> {
    T response;

    public T getResponse () { return response; }
    public void setResponse(T response) {this.response = response;}
}
Run Code Online (Sandbox Code Playgroud)

所以如果我想做这样的事情,一切都好.

public ResponseWrapper<MyClass> makeRequest(URI uri) {
    ResponseEntity<ResponseWrapper<MyClass>> response = template.exchange(
        uri,
        HttpMethod.POST,
        null,
        new ParameterizedTypeReference<ResponseWrapper<MyClass>>() {});
    return response;
}
Run Code Online (Sandbox Code Playgroud)

但是当我试图创建上述方法的通用变体时......

public <T> ResponseWrapper<T> makeRequest(URI uri, Class<T> …
Run Code Online (Sandbox Code Playgroud)

java generics spring jackson resttemplate

53
推荐指数
5
解决办法
7万
查看次数

如何使用注释自动装配RestTemplate

当我尝试自动装配Spring RestTemplate时,我收到以下错误:

nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.web.client.RestTemplate] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.

在注释驱动的环境中使用Spring 4.

我的调度程序servlet配置如下:

<context:component-scan base-package="in.myproject" />
<mvc:default-servlet-handler />    
<mvc:annotation-driven />
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/>
Run Code Online (Sandbox Code Playgroud)

我尝试自动装配RestTemplate的课程如下:

@Service("httpService")
public class HttpServiceImpl implements HttpService {

@Autowired
private RestTemplate restTemplate;

@Override
public void sendUserId(String userId){

    MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
    map.add("userId", userId);
    map.add("secretKey", "kbhyutu7576465duyfy");

    restTemplate.postForObject("http://localhost:8081/api/user", map, null);


    }
}
Run Code Online (Sandbox Code Playgroud)

java spring spring-mvc resttemplate

52
推荐指数
6
解决办法
9万
查看次数

HTTP使用RestTemplate获取标头

如何使用Spring RestTemplate发送GET请求?其他问题使用POST,但我需要使用GET.当我运行它时,程序继续工作,但似乎网络被阻塞,因为这是在AsyncTask中,当我在单击此按钮后尝试运行另一个asynctask时,它们将无法工作.

我试过了

        String url = "https://api.blah.com/2.0/search/cubes?w=jdfkl&whitespace=1";

        MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
        map.add("Bearer", accessToken);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); //copied this from somewhere else, not sure what its for

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);

        HttpMessageConverter<String> stringConverter = new StringHttpMessageConverter();
        FormHttpMessageConverter formConverter = new FormHttpMessageConverter();
        List<HttpMessageConverter<?>> msgConverters = new ArrayList<HttpMessageConverter<?>>();


        msgConverters.add(formConverter);
        msgConverters.add(new MappingJacksonHttpMessageConverter());
        msgConverters.add(stringConverter); 

        template.setMessageConverters(msgConverters);
        //SetSearchResponseData is my custom class to store the incoming JSON
        ResponseEntity<SetSearchResponseData> result = template.exchange(url, HttpMethod.GET, request, SetSearchResponseData.class);
        //If I was …
Run Code Online (Sandbox Code Playgroud)

spring android get http resttemplate

49
推荐指数
2
解决办法
7万
查看次数

如何使用Spring RestTemplate禁用SSL证书检查?

我正在尝试编写集成测试,我们的测试使用Simple启动嵌入式HTTPS服务器.我创建了一个自签名证书,keytool并且能够使用浏览器访问服务器(特别是Chrome,我收到有关自签名证书的警告).

但是,当我尝试使用Spring RestTemplate进行连接时,我得到一个ResourceAccessException:

org.springframework.web.client.ResourceAccessException: I/O error on GET request for "https://localhost:8088":sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target; nested exception is javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:557)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:502)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:444)
    at net.initech.DummySslServer.shouldConnect(DummySslServer.java:119)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27) …
Run Code Online (Sandbox Code Playgroud)

java spring self-signed resttemplate

44
推荐指数
5
解决办法
8万
查看次数

spring mvc rest service redirect/forward/proxy

我使用spring mvc框架构建了一个Web应用程序来发布REST服务.例如:

@Controller
@RequestMapping("/movie")
public class MovieController {

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public @ResponseBody Movie getMovie(@PathVariable String id, @RequestBody user) {

    return dataProvider.getMovieById(user,id);

}
Run Code Online (Sandbox Code Playgroud)

现在我需要部署我的应用程序,但是我遇到以下问题:客户端无法直接访问应用程序所在的计算机(有防火墙).因此,我需要在代理机器上(可由客户端访问)调用实际的休息服务的重定向层.

我尝试使用RestTemplate进行新的调用:例如:

@Controller
@RequestMapping("/movieProxy")
public class MovieProxyController {

    private String address= "http://xxx.xxx.xxx.xxx:xx/MyApp";

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public @ResponseBody Movie getMovie(@PathVariable String id,@RequestBody user,final HttpServletResponse response,final HttpServletRequest request) {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.exchange( address+ request.getPathInfo(), request.getMethod(), new HttpEntity<T>(user, headers), Movie.class);

}
Run Code Online (Sandbox Code Playgroud)

这没关系,但我需要重写控制器中的每个方法以使用resttemplate.此外,这会导致代理计算机上的冗余序列化/反序列化.

我尝试使用restemplate编写泛型函数,但它没有用完:

@Controller …
Run Code Online (Sandbox Code Playgroud)

java spring-mvc resttemplate spring-boot

43
推荐指数
5
解决办法
5万
查看次数

使用Spring RestTemplate访问Https Rest服务

任何人都可以使用Spring rest模板为我提供代码示例来访问使用https保护的休息服务URL.

我有证书,用户名和密码.基本身份验证在服务器端使用,我想创建一个客户端,可以使用提供的证书,用户名和密码(如果需要)连接到该服务器.

rest https spring certificate resttemplate

42
推荐指数
3
解决办法
8万
查看次数

RestTemplate:如何一起发送URL和查询参数

我试图传递路径参数和查询URL中的参数,但我得到一个奇怪的错误.下面是代码

    String url = "http://test.com/Services/rest/{id}/Identifier"
    Map<String, String> params = new HashMap<String, String>();
    params.put("id", "1234");
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url)
                                        .queryParam("name", "myName");
    String uriBuilder = builder.build().encode().toUriString();
    restTemplate.exchange(uriBuilder , HttpMethod.PUT, requestEntity,
                    class_p, params);
Run Code Online (Sandbox Code Playgroud)

我的网址正在变成 http://test.com/Services/rest/%7Bid%7D/Identifier?name=myName

我该怎么做才能让它发挥作用.我期待http://test.com/Services/rest/{id}/Identifier?name=myNameparams将id添加到url

请建议.提前致谢

java query-parameters url-parameters resttemplate path-parameter

41
推荐指数
3
解决办法
10万
查看次数