REST 인터페이스 설계에서 인터페이스 테스트를 위해 RestTemplate를 사용하는 것이 일반적인 방법이지만, 사용하는 동안 많은 방법과 매개 변수로 인해 많은 학생들이 양식 제출 및 페이로드 제출 방법의 차이점을 혼동했습니다. 또한 인터페이스 디자인은 기존 브라우저에서 사용하는 제출 방법과 다릅니다. 405 오류와 같은 다양한 오류가 발생하거나 제출 된 데이터를 전혀 얻을 수 없습니다. 오류 샘플은 다음과 같습니다.
스레드의 예외 "main"org.springframework.web.client.httpclienterRorexception : 405 메소드가 허용되지 않습니다
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.exchange (resttemplate.java:531)
1. 교환 방법을 사용하여 제출하십시오
Exchange는 사후 방법과 GETS를 모두 실행할 수 있으므로 가장 널리 사용되며 사용법은 다음과 같습니다.
String URL = "http : // localhost/mirana-ee/app/login"; resttemplate client = new resttemplate (); httpheaders headers = new httpheaders (); //이 제출 방법을 쉽게 변경하지 마십시오. 대부분의 경우, 제출 방법은 양식 제출 헤더입니다. SetContentType (mediaType.application_form_urlencoded); // 매개 변수를 캡슐화하고, 맵 및 해시 맵으로 바꾸지 마십시오. 그렇지 않으면 매개 변수는 multivaluemap <string, params = new LinkedMultivaluememap <string (string)을 전달할 수 없습니다. "username"); params.add ( "password", "123456"); httpentity <multivaluemap <string, string >> requestentity = new httpentity <multivaluemap <string, string >> (params, headers); // execute http 요청 응답 <문자열> 응답 = client.exithange (url, httpmethod, httpmethod, httpmethod. String.class); // output result system.out.println (response.getBody ());
2. 포스트 포지티와 함께 제출하십시오
포스트 퓨터는 교환의 단순화이며 다음과 같이 httpmethod.post 매개 변수의 감소 만 있으면됩니다.
// 위의 코드는 정확히 동일합니다. // 교환 메소드를 바꾸면 만 필요합니다. 응답 <문자열> 응답 = client.postforentity (url, requestentity, string.class);
3. 양식 제출과 페이로드 제출의 차이에 대해
컨트롤러 메소드 매개 변수에서 "@ModelAttribute"를 "@RequestBody"주석으로 변경하면 제출 방법은 Payload 메소드입니다. 코드 예제는 다음과 같습니다.
// @requestbody annotation @requestmapping (value = "/login", method = requestmethod.post, confumts = "application/json") // @ModelAttribute를 추가하지 않으면 @ModelAttribute를 추가하지 않으면 공개 계정 getAccount ( @modelattribute @requestior acumaching) {requestior accession (@requestior accession) {requestbody acression (@Requestior Arcumes) {request body @modelattover comport. 날짜()); 반품 계정;}다시 한번,“@ModelAttribute”를 다시 추가하지 마십시오. 우선 순위가 상대적으로 높기 때문에 시스템은 양식을 사용하여 제출 된 컨텐츠를 구문 분석합니다.
페이로드 방법의 경우 제출 된 컨텐츠는 문자열이어야하며 헤더는 "Application/JSON"으로 설정해야합니다. 예제는 다음과 같습니다.
// 주소 요청 문자열 url = "http : // localhost/mirana-ee/app/login"; resttemplate client = new resttemplate (); // headerhttppheaders headers = new httpheaders (); headers.setconttype (mediaType.application_json_utf8); Bean Injection을 통한 ObjectMapperObjectMapper Mapper = new ObjectMapper (); map <string, string> params = maps.newhashmap (); params.put ( "username", "inter"); params.put ( "password", "123456"); String value = mapper.writevalueasstring (params); httpentity = news = new httpentity <string> (값, 헤더); // http request responseentity <strestentity = client.postforentity (url, requestentity, string.class); system.out.println (response.getbody ());
문자열 모드로 내용이 제출되지 않으면 다음 오류가 확실히 나타납니다.
스레드의 예외 "main"org.springframework.web.client.httpclienterRorexception : 400 잘못된 요청
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.postforentity (resttemplate.java:407)
마지막으로 @requestbody를 통해 요청 매개 변수를 얻을 수 없다는 점을 강조해야합니다. 위 서버의 코드가 다음 형식으로 변경되면 데이터를 확실히 얻지 못하지만 양식 제출에는 반대가 사실입니다.
@requestmapping (value = "/login", consumer = "application/json", method = requestmethod.post) 공개 계정 getAccount (@requestbody 계정, httpservletrequest request) {// 매개 변수 value system.out.println ( "username")을 가져 오지 않아야합니다. ac 반품 계정;}4. httpentity의 구조
httpentity는 HTTP 요청의 캡슐화로 헤더와 신체의 두 부분을 포함합니다. 헤더는 요청 헤더를 설정하는 데 사용되며 본문은 요청 본문을 설정하는 데 사용되므로 생성자는 다음과 같습니다.
// 값은 요청 본문입니다 // 헤더는 요청 헤더 httpentity httpentity <string> requestentity = new httpentity <string> (값, 헤더);
5. httpentity 및 urivariableble
resttemplate의 사용에서 httpentity는 특정 매개 변수 값을 전달하는 데 사용되는 반면 Urivariableble은 주소 매개 변수 대신 HTTP 주소를 포맷하는 데 사용됩니다. 올바른 사용법은 다음과 같습니다.
// 포맷 매개 변수 추가 PATHSTRING url = "http : // localhost/mirana-ee/app/{path}"; // 포맷 매개 변수 준비 map <string, string> varparams = maps.newhashmap (); varparams.put ( "path", "login"; client.postforentity (url, requestentity, string.class, varparams);6. httpmessageconverter에 대한 참고 사항
온라인에서 많은 예에서 많은 사람들이 페이로드 제출물을 처리하기 위해 사용자 정의 httpmessageconverter를 추가 한 것을 발견했습니다.
// client.getMessageConverters (). add (new Mapping Jackson2httpMessageConverter ()); client.getMessageConverters (). add (new StringHttpMessageConverter ());
그런 다음 소스 코드를 확인하고 디버깅 한 후 resttemplate에 7 가지 유형의 HTTPMESSAGECONVERTER가 내장되어 있음을 알았습니다.
1. org.springframework.http.converter.bytearrayhttpmessageconverter
2. org.springframework.http.converter.stringhttpmessageconverter
3. org.springframework.http.converter.resourcehttpmessageconverter
4. org.springframework.http.converter.xml.sourcehttpmessageconverter
5. org.springframework.http.converter.support.allenCompassingformhttpmessageConverter
6. org.springframework.http.converter.xml.jaxb2rootelementhttpmessageconverter
7. org.springframework.http.converter.json.mappingjackson2httpmessageconverter
“`
결론적으로
RestTemplate은 양식 데이터 제출의 어려움을 크게 단순화 할 수 있으며 JSON 데이터를 자동으로 변환하는 기능이 제공됩니다. 그러나 httpentity (헤더 및 신체)의 구성 구조를 이해하고 urivariable에 대한 차이를 이해 함으로써만 사용량을 이해할 수 있습니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.