我要在post请求的主体中传递键值对.但是当我运行我的代码时,我得到错误为"无法写入请求:找不到合适的HttpMessageConverter请求类型[org.springframework.util.LinkedMultiValueMap]和内容类型[text/plain]"
我的代码如下:
MultiValueMap<String, String> bodyMap = new LinkedMultiValueMap<String, String>();
bodyMap.add(GiftangoRewardProviderConstants.GIFTANGO_SOLUTION_ID, giftango_solution_id);
bodyMap.add(GiftangoRewardProviderConstants.SECURITY_TOKEN, security_token);
bodyMap.add(GiftangoRewardProviderConstants.REQUEST_TYPE, request_type);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(bodyMap, headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> model = restTemplate.exchange(giftango_us_url, HttpMethod.POST, request, String.class);
String response = model.getBody();
Run Code Online (Sandbox Code Playgroud) 我对PersonDTO有以下定义:
public class PersonDTO
{
private String id
private String firstName;
private String lastName;
private String maritalStatus;
}
Run Code Online (Sandbox Code Playgroud)
这是一个示例记录:
{
"id": 1,
"firstName": "John",
"lastName": "Doe",
"maritalStatus": "married"
}
Run Code Online (Sandbox Code Playgroud)
现在,John Doe离婚了.所以我需要向这个URL发送一个PATCH请求:
http://localhost:8080/people/1
Run Code Online (Sandbox Code Playgroud)
使用以下请求正文:
{
"maritalStatus": "divorced"
}
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚该怎么做.这是我到目前为止尝试的内容:
// Create Person
PersonDTO person = new PersonDTO();
person.setMaritalStatus("Divorced");
// Create HttpEntity
final HttpEntity<ObjectNode> requestEntity = new HttpEntity<>(person);
// Create URL (for eg: localhost:8080/people/1)
final URI url = buildUri(id);
ResponseEntity<Void> responseEntity = restTemplate.exchange(url, HttpMethod.PATCH, requestEntity, Void.class);
Run Code Online (Sandbox Code Playgroud)
以下是上述问题:
1)由于我只设置MaritalStatus,其他字段都将为null.因此,如果我打印出请求,它将如下所示:
{
"id": null,
"firstName": …Run Code Online (Sandbox Code Playgroud) Abstract控制器类需要REST中的对象列表.使用Spring RestTemplate时,它不会将其映射到所需的类,而是返回Linked HashMAp
public List<T> restFindAll() {
RestTemplate restTemplate = RestClient.build().restTemplate();
ParameterizedTypeReference<List<T>> parameterizedTypeReference = new ParameterizedTypeReference<List<T>>(){};
String uri= BASE_URI +"/"+ getPath();
ResponseEntity<List<T>> exchange = restTemplate.exchange(uri, HttpMethod.GET, null,parameterizedTypeReference);
List<T> entities = exchange.getBody();
// here entities are List<LinkedHashMap>
return entities;
}
Run Code Online (Sandbox Code Playgroud)
如果我用,
ParameterizedTypeReference<List<AttributeInfo>> parameterizedTypeReference =
new ParameterizedTypeReference<List<AttributeInfo>>(){};
ResponseEntity<List<AttributeInfo>> exchange =
restTemplate.exchange(uri, HttpMethod.GET, null,parameterizedTypeReference);
Run Code Online (Sandbox Code Playgroud)
它工作正常.但不能放入所有子类,任何其他解决方案.
实际上这个restTemplate.exchange()方法做了什么?
@RequestMapping(value = "/getphoto", method = RequestMethod.GET)
public void getPhoto(@RequestParam("id") Long id, HttpServletResponse response) {
logger.debug("Retrieve photo with id: " + id);
// Prepare acceptable media type
List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
acceptableMediaTypes.add(MediaType.IMAGE_JPEG);
// Prepare header
HttpHeaders headers = new HttpHeaders();
headers.setAccept(acceptableMediaTypes);
HttpEntity<String> entity = new HttpEntity<String>(headers);
// Send the request as GET
ResponseEntity<byte[]> result =
restTemplate.exchange("http://localhost:7070/spring-rest-provider/krams/person/{id}",
HttpMethod.GET, entity, byte[].class, id);
// Display the image
Writer.write(response, result.getBody());
}
Run Code Online (Sandbox Code Playgroud) 的方法RestTemplate,如postForEntity()抛RestClientException.我想从catch块中的异常对象中提取HTTP状态代码和响应主体.我怎样才能做到这一点?
我的授权服务在成功时返回http 204,在失败但是没有responseBody时返回http 401.我无法使用RestTemplate客户端使用它.它无法尝试序列化响应.杰克逊的错误表明我打开了序列化程序中的FAIL_ON_EMPTY_BEANS,但是如何在restTemplate中设置它
客户消耗其余的api
@SuppressWarnings("rawtypes")
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
RestTemplate restTemplate = new RestTemplate();
System.out.println("\n\n\n\n ============API REQUEST INTERCEPTOR=============== \n\n\n\n\n");
if(StringUtils.isBlank(request.getHeader(AuthenticationKeys.AUTHENTICATIONTOKEN.name().toLowerCase()))){
//TODO AUTHORIZE TOKEN
ResponseEntity<AuthenticationResponse> authenticateResponse = restTemplate.getForEntity(authenticateUrl, AuthenticationResponse.class);
if(authenticateResponse.getStatusCode().is2xxSuccessful()){
//TODO SET THE TOKEN IN THE CONTEXT
return true;
}else{
//TODO DO SOME ERROR HANDLING
return false;
}
}else{
AuthorizationRequest authorizationRequest = new AuthorizationRequest();
authorizationRequest.setToken("TESTNG");
ResponseEntity<Object> authorizationResponse = restTemplate.postForEntity(authorizeUrl, request, Object.class);
if(authorizationResponse.getStatusCode().is2xxSuccessful()){
return true;
}else{
//TODO DO SOME ERROR HANDLING
if(authorizationResponse.getStatusCode().equals(HttpStatus.UNAUTHORIZED)){
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Oops! …Run Code Online (Sandbox Code Playgroud) 我正在尝试将带有RestTemplate的文件上传到带有Jetty的Raspberry Pi.在Pi上有一个运行的servlet:
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
PrintWriter outp = resp.getWriter();
StringBuffer buff = new StringBuffer();
File file1 = (File) req.getAttribute("userfile1");
String p = req.getParameter("path");
boolean success = false;
if (file1 == null || !file1.exists()) {
buff.append("File does not exist\n");
} else if (file1.isDirectory()) {
buff.append("File is a directory\n");
} else {
File outputFile = new File(req.getParameter("userfile1"));
if(isValidPath(p)){
p = DRIVE_ROOT + p;
final File finalDest = new File(p
+ outputFile.getName());
success = false;
try …Run Code Online (Sandbox Code Playgroud) 我正在学习Spring Framework来创建一个REST Web服务的客户端,该服务使用基本身份验证并交换JSON.经过网上搜索后,我编写了一些有用的代码(下图),但现在我收到了"不支持的媒体类型"错误,因为请求是使用Content-Type text/plain而不是application/json发送的.我在网上找不到任何显示如何在请求标题中设置Content-Type的内容(不会在杂草中完全丢失).我的代码是:
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
...
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("login", "password"));
HttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
String url = "http://host:8080/path/";
String postBody = getPostInput("filename");
jsonString = restTemplate.postForObject(path, postBody, String.class);
Run Code Online (Sandbox Code Playgroud)
任何指导将不胜感激.
谢谢,乔治
我试图获取数据,但总是让403(Forbidden)与RestTemplate.
但是当我尝试时org.apache.http.client.HttpClient,一切都很好.我也可以在我的机器上使用Postman获取数据.
代码很简单但我不知道什么是错的.
public Object get() {
try {
RestTemplate restTemplate = new RestTemplate();
Object result = restTemplate.getForObject("https://api.hearthstonejson.com/v1/19776/enUS/cards.json", Object.class);
return result;
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:附加堆栈跟踪
org.springframework.web.client.HttpClientErrorException: 403 Forbidden
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:63)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:287)
at com.brawlstone.metaservice.service.SyncService.get(SyncService.java:49)
at com.brawlstone.metaservice.web.SyncController.getCards(SyncController.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967) …Run Code Online (Sandbox Code Playgroud) 我尝试使用弹簧RestTemplate.getForObject()访问休息端点,但我的uri变量未展开,并作为参数附加到url.这是我到目前为止所得到的:
Map<String, String> uriParams = new HashMap<String, String>();
uriParams.put("method", "login");
uriParams.put("input_type", DATA_TYPE);
uriParams.put("response_type", DATA_TYPE);
uriParams.put("rest_data", rest_data.toString());
String responseString = template.getForObject(endpointUrl, String.class, uriParams);
Run Code Online (Sandbox Code Playgroud)
endpointUrl变量的值是,http://127.0.0.1/service/v4_1/rest.php并且它的确是它所谓的,但我希望http://127.0.0.1/service/v4_1/rest.php?method=login&input_type...被调用.任何提示都表示赞赏.
我正在使用Spring 3.1.4.RELEASE
问候.
resttemplate ×10
java ×6
spring ×5
rest ×3
content-type ×1
jackson ×1
json ×1
post ×1
spring-boot ×1
spring-rest ×1
spring-web ×1