有人可以告诉我如何使用RestTemplate使用Authorization来发布HttpEntity对象。我在测试应用程序中使用以下代码
客户端:
public class FifthWay extends Thread {
public void run() {
String plainCreds = "anuj:khare";
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Creds);
HttpEntity<String> postRequest = new HttpEntity<String>("FifthWay",headers);
RestTemplate rt = new RestTemplate();
rt.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
rt.getMessageConverters().add(new StringHttpMessageConverter());
String postUri = new String("http://169.194.48.182:8080/trade-capture-service/deals/persist");
ResponseEntity<String> responseForPost = rt.exchange(postUri,HttpMethod.POST, postRequest, String.class);
String responseStringForPost = responseForPost.getBody();
System.out.println(responseStringForPost);
}
}
服务器端:
@Controller
@RequestMapping("/deals")
public class RestController {
...
...
@RequestMapping(value = "/check", method = RequestMethod.GET)
public @ResponseBody
String justACheck() {
System.out.println("It Works");
return "It works";
}
得到如下错误:
Exception in thread "Thread-4" org.springframework.web.client.HttpClientErrorException: 415 Unsupported Media Type
OR
Exception in thread "Thread-4" org.springframework.web.client.HttpClientErrorException: 400 Bad Request
请帮忙
答案 0 :(得分:0)
以下是RestTemplate交换的示例:
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
HttpHeaders requestHeaders = new HttpHeaders();
final HttpEntity entity = new HttpEntity(restCanvas, requestHeaders);
return restTemplate.exchange(canvasAddUrl + value, HttpMethod.POST, entity, Integer.class);
这里canvasAddURL是您希望使用context-path调用的URL。如果你想给它添加一个cookie,知道,我已经删除了那段代码,因为大部分时间都没有必要。返回值为ResponseEntity<Integer>
。看看这个。