我正在使用 maven 和 spring resttemplate 开发 android 应用程序。
这是我的 pom.xml
<properties>
<platform.version> 2.3.3</platform.version>
<spring.version>1.0.0.RELEASE</spring.version>
<simple-version>2.4.1</simple-version>
</properties>
<dependencies>
<!-- Spring Android Core -->
<dependency>
<groupId>org.springframework.android</groupId>
<artifactId>spring-android-core</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring Rest Android -->
<dependency>
<groupId>org.springframework.android</groupId>
<artifactId>spring-android-rest-template</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Using Jackson for JSON marshaling -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.7.1</version>
</dependency>
<!-- Using Simple for XML marshaling -->
<dependency>
<groupId>org.simpleframework</groupId>
<artifactId>simple-xml</artifactId>
<version>${simple-version}</version>
<exclusions>
<exclusion>
<artifactId>stax</artifactId>
<groupId>stax</groupId>
</exclusion>
<exclusion>
<artifactId>stax-api</artifactId>
<groupId>stax</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>com.jayway.maven.plugins.android.generation2</groupId>
<artifactId>android-maven-plugin</artifactId>
<version>3.1.1</version>
<configuration>
<androidManifestFile>${project.basedir}/AndroidManifest.xml</androidManifestFile> …Run Code Online (Sandbox Code Playgroud) String url = "https://api.assembla.com/token?";
RestTemplate restTemplate = new RestTemplate();
MultiValueMap<String, String> body =
new LinkedMultiValueMap<String, String>();
body.add("client_id", "myid");
body.add("client_secret", "mysecret");
body.add("grant_type", "client_credentials");
HttpHeaders headers = new HttpHeaders();
headers.add("Accept", "application/json");
headers.add("Content-type", "application/json");
HttpEntity<?> entity = new HttpEntity<Object>(body, headers);
ResponseEntity<JsonResponseType> res =
restTemplate.exchange(url, HttpMethod.POST, entity, JsonResponseType.class);
System.out.println("Hello....." + res);
Run Code Online (Sandbox Code Playgroud)
我收到 401 未经授权的错误,有人可以删除它吗
也用
MultiValueMap<String, String> body =
new LinkedMultiValueMap<String, String>();
body.add("x-api-key", "myapikey");
body.add("x-api-secret", "myapisecret");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Accept", "application/json");
headers.set("Content-type", "application/json");
HttpEntity<?> entity = new HttpEntity<Object>(body, headers);
entity.getHeaders().setContentType(MediaType.APPLICATION_JSON);
RestTemplate …Run Code Online (Sandbox Code Playgroud) 我必须实例化一个类,它使用@class中的信息从JSON扩展抽象类,如下所示.
"name": {
"health": "xxx",
"animal": {
"_class": "com.example.Dog",
"height" : "20"
"color" : "white"
}
},
Run Code Online (Sandbox Code Playgroud)
这里抽象类是动物,狗延伸动物类.因此,使用@class中的信息,我们可以直接实例化狗.这也是我在restTemplate中得到的回应
ResponseEntity<List<SomeListName>> response = restTemplate.exchange("http://10.150.15.172:8080/agencies", HttpMethod.GET, request, responseType);
Run Code Online (Sandbox Code Playgroud)
执行此行时会出现以下错误.由于POJO类是自动生成的,我不能使用像@JsonTypeInfo这样的注释
我正在使用Spring boot和maven.此错误将在控制台中出现.
无法读取JSON:无法构造"MyPOJO"的实例,问题:抽象类型需要映射到具体类型,具有自定义反序列化器,或者使用其他类型信息进行实例化
我正在使用 restTemplate 从远程服务器使用 json 数据,然后使用 jackson 解析我的 java 对象中的 json。我已通过 java 代码将所需的消息转换器添加到我的 restTemplate 中:
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
messageConverters.add(new FormHttpMessageConverter());
messageConverters.add(new StringHttpMessageConverter());
messageConverters.add(new MappingJacksonHttpMessageConverter());
restTemplate.setMessageConverters(messageConverters);
restTemplate.setRequestFactory(new CommonsClientHttpRequestFactory());
MyResponse myResponse = restTemplate.getForObject(caasUrl, MyResponse.class);
Run Code Online (Sandbox Code Playgroud)
我的 restTemplate 在我的 spring-config 文件中定义为:
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<constructor-arg>
<bean class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
<property name="readTimeout" value="630000" />
<property name="connectTimeout" value="30000" />
</bean>
</constructor-arg>
</bean>
Run Code Online (Sandbox Code Playgroud)
它工作正常,现在我的问题是我们如何将消息转换器列表传递给 xml 配置中的 restTemplate,因为我不想通过 java 代码做同样的事情。任何帮助请
我正在编写 JUnit 测试,通过 RestTemplate 调用我的应用程序。我已经成功地实现了 GET、POST 和 PUT,但无法运行 PATCH(尽管它在客户端发送 URL 时工作)。例如,使用以下代码运行 POST:
RestTemplate restTemplate = new RestTemplate();
ProductModel postModel = restTemplate.postForObject(TestBase.URL + URL, pModel, ProductModel.class);
Run Code Online (Sandbox Code Playgroud)
但是当我尝试调用 restTemplate.patchForObject() - 我在网上找到的 - STS 返回一个错误,指出该函数未定义。我因此使用了这个:
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<MessageModel> retval = restTemplate.exchange("http://localhost:8080/products/batchUpdateProductPositions",
HttpMethod.PATCH, new HttpEntity<ProductPositionListModel>(pps), MessageModel.class);
Run Code Online (Sandbox Code Playgroud)
它编译,但给了我一个错误:
I/O Error on PATCH request for "http://localhost:8080/products/batchUpdateProductPositions": Invalid HTTP method: PATCH
Run Code Online (Sandbox Code Playgroud)
在应用程序中,我在 Controller 类中定义了操作:
@RequestMapping(value = "/batchUpdateProductPositions", method = RequestMethod.PATCH)
public MessageModel batchUpdatePosition(
@RequestBody ProductPositionListModel productPositionList)
throws Exception {
try {
return productService.batchUpdatePosition(productPositionList);
} …Run Code Online (Sandbox Code Playgroud) String url = serverUrl + metadata.getUri();
response = restTemplate.exchange(url, metadata.getAction(), requestEntity, metadata.getResponseType());
Run Code Online (Sandbox Code Playgroud)
url 包含字符串
https://localhost/api/fm/info/dump/a \b\f\20170722_225714.jpg?lastModified=1507881481909
Spring RestTemplate 在请求服务器时将其编码为以下内容
https://localhost/api/fm/info/dump/a%5Cb%5Cf%5C20170722_225714.jpg?lastModified=1507881481909
仅供参考,我需要禁用 URL 编码,以便 '\' 字符在服务器端可用,因为这是一项业务要求,因为我们的 Web 服务器 (Nginx) 已配置为根据包含 '\ ' 特点。
我编写了货币转换器程序,它JSON从api.fixer.io、映射对象中读取并创建选定汇率的简单数据集。我的程序运行良好,直到我停止使用Jackson解析和映射对象并将其替换为RestTemplate. 它可以很好地读取基础货币和日期,但不能很好地读取Rates子对象。为什么?
我的代码:
Currency类:
package com.github.gromo13.currencyConverter.model.util;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Currency {
private String base;
private String date;
private Rates rates;
public Currency() {
}
public String getBase() {
return this.base;
}
public void setBase(String base) {
this.base = base;
}
public String getDate() {
return this.date;
}
public void setDate(String date) {
this.date = date;
}
public Rates getRates() {
return this.rates;
}
public void …Run Code Online (Sandbox Code Playgroud) 我正在使用 Spring REST 模板来调用外部公共 REST API。作为 API 身份验证的一部分,我需要在标头中发送用户密钥。我不确定如何在 Spring REST 模板 GET 调用中设置自定义标头属性。
RestTemplate restTemplate = new RestTemplate();
<Class> object = restTemplate.getForObject("<url>","<class type>");
Run Code Online (Sandbox Code Playgroud)
我发现这可以通过设置 set("key","value")用HttpHeaders类来完成,但没有找到任何具体的例子。如果您有任何信息,请告诉我。
我正在尝试模拟这个使用 rest 模板调用 API 并返回一个列表的服务。
我无法模拟该restTemplate.exchange()方法。它给了我一个“java.lang.IllegalArgumentException:URI 不是绝对的”异常。
编辑-我愚蠢的自己忘记在测试用例中将 http:// 放在基本 url 之前,这就是我得到它的原因。感谢您的帮助并为浪费您的时间道歉。
测试方法
@Value("${base-url}")
private String baseUrl;
@Override
public List<Currency> getCurrencyList() {
RestTemplate restTemplate = new RestTemplate();
String url = baseUrl + "/currency";
ResponseEntity<List<Currency>> result;
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> dataHttpEntity = new HttpEntity<>(headers);
log.info(url);
result = restTemplate.exchange(url, HttpMethod.GET,dataHttpEntity, new ParameterizedTypeReference<List<Currency>>() {
});
return result.getBody();
}
Run Code Online (Sandbox Code Playgroud)
测试代码
@Test
public void getCurrencyListTest() {
ResponseEntity<List<Currency>> result = ResponseEntity.ok(currencyList);
when(restTemplate.exchange( ArgumentMatchers.anyString(),
ArgumentMatchers.any(HttpMethod.class),
ArgumentMatchers.any(),
ArgumentMatchers.<Class<List<Currency>>>any())).thenReturn(result);
assertEquals(currencyList,service.getCurrencyList());
}
Run Code Online (Sandbox Code Playgroud)
例外
java.lang.IllegalArgumentException: URI …Run Code Online (Sandbox Code Playgroud) 我对外部RESTful api进行了get请求,并接收具有以下结构的json对象作为响应:
{
"data": {
"id": 1,
"name": "John Doe",
"email": "doe@john.com",
"urlPicture": "urlPicture.com/82819",
"address": {
"street": "My street",
"number": "29",
"city": "Nurnberg",
"country": "Germany"
}
}
}
Run Code Online (Sandbox Code Playgroud)
我不需要此响应的所有内容,我只希望将某些字段保存在数据库中。
我的POJO类类似于此伪代码:
{
"data": {
"id": 1,
"name": "John Doe",
"email": "doe@john.com",
"urlPicture": "urlPicture.com/82819",
"address": {
"street": "My street",
"number": "29",
"city": "Nurnberg",
"country": "Germany"
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试提取所需的字段时,在此字段中收到null
public class Data{
private User user;
// getters and setters
}
public class User{
private int id;
private String name;
private String urlPicture; …Run Code Online (Sandbox Code Playgroud) resttemplate ×10
java ×6
spring ×4
jackson ×2
rest ×2
spring-boot ×2
android ×1
gson ×1
http-patch ×1
json ×1
junit ×1
mockito ×1
spring-json ×1
spring-mvc ×1
spring-rest ×1
url-encoding ×1