有人可以告訴我如何使用RestTemplate來使用Authorization發佈HttpEntity對象。如何使用RestTemplate請求POST,使用用戶密碼授權
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
請幫
服務器端: @Controller @RequestMapping( 「/交易」) 公共類RestController { ... – Kaku
嘗試'exchange' RestTemplate的。你可以用POST和GET來完成。 –
我在做只使用交換,但沒有幫助 – Kaku