/** * <strong>Spring's central class for synchronous client-side HTTP access.</strong> * It simplifies communication with HTTP servers, and enforces RESTful principles. * It handles HTTP connections, leaving application code to provide URLs * (with possible template variables) and extract results. * * <p><strong>Note:</strong> by default the RestTemplate relies on standard JDK * facilities to establish HTTP connections. You can switch to use a different * HTTP library such as Apache HttpComponents, Netty, and OkHttp through the * {@link #setRequestFactory} property. * * <p>The main entry points of this template are the methods named after the six main HTTP methods: * <table> * <tr><th>HTTP method</th><th>RestTemplate methods</th></tr> * <tr><td>DELETE</td><td>{@link #delete}</td></tr> * <tr><td>GET</td><td>{@link #getForObject}</td></tr> * <tr><td></td><td>{@link #getForEntity}</td></tr> * <tr><td>HEAD</td><td>{@link #headForHeaders}</td></tr> * <tr><td>OPTIONS</td><td>{@link #optionsForAllow}</td></tr> * <tr><td>POST</td><td>{@link #postForLocation}</td></tr> * <tr><td></td><td>{@link #postForObject}</td></tr> * <tr><td>PUT</td><td>{@link #put}</td></tr> * <tr><td>any</td><td>{@link #exchange}</td></tr> * <tr><td></td><td>{@link #execute}</td></tr> </table> * * <p>In addition the {@code exchange} and {@code execute} methods are generalized versions of * the above methods and can be used to support additional, less frequent combinations (e.g. * HTTP PATCH, HTTP PUT with response body, etc.). Note however that the underlying HTTP * library used must also support the desired combination. * * <p>For each HTTP method there are three variants: two accept a URI template string * and URI variables (array or map) while a third accepts a {@link URI}. * Note that for URI templates it is assumed encoding is necessary, e.g. * {@code restTemplate.getForObject("http://example.com/hotel list")} becomes * {@code "http://example.com/hotel%20list"}. This also means if the URI template * or URI variables are already encoded, double encoding will occur, e.g. * {@code http://example.com/hotel%20list} becomes * {@code http://example.com/hotel%2520list}). To avoid that use a {@code URI} method * variant to provide (or re-use) a previously encoded URI. To prepare such an URI * with full control over encoding, consider using * {@link org.springframework.web.util.UriComponentsBuilder}. * * <p>Internally the template uses {@link HttpMessageConverter} instances to * convert HTTP messages to and from POJOs. Converters for the main mime types * are registered by default but you can also register additional converters * via {@link #setMessageConverters}. * * <p>This template uses a * {@link org.springframework.http.client.SimpleClientHttpRequestFactory} and a * {@link DefaultResponseErrorHandler} as default strategies for creating HTTP * connections or handling HTTP errors, respectively. These defaults can be overridden * through {@link #setRequestFactory} and {@link #setErrorHandler} respectively. * * @author Arjen Poutsma * @author Brian Clozel * @author Roy Clarkson * @author Juergen Hoeller * @since 3.0 * @see HttpMessageConverter * @see RequestCallback * @see ResponseExtractor * @see ResponseErrorHandler * @see AsyncRestTemplate */
重載的3個方法怎麼選擇呢?建議選擇URL參數類型爲String的那個兩個方法。由於當這個參數是一個非URI格式的,須要進行轉換,而URI的構造函數會拋出一個檢查異常URISyntaxException,該異常必須捕獲。另外兩個重載方法則避免了捕獲異常,因此上面表格中推薦的方法的第一個參數都是String類型。html
package com.practice; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; import net.sf.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.springframework.http.HttpEntity; import org.springframework.http.ResponseEntity; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; public class RestTemplateTest extends TestCase { RestTemplate restTpl; @Before public void setUp() { restTpl = new RestTemplate(); } @Test public void testGet() { Map<String, Object> paramsMap = new HashMap<String, Object>(); paramsMap.put("cityCode", "xxxxxxxxxx"); paramsMap.put("key", "xxxxxxxxxxxxxxxxxxxxx"); String url = "http://xxx.xxx.xxx.xxx:8080/xxx/xxxx?xxxx&config=xxx&cityCode={cityCode}&key={key}"; String respStr = restTpl.getForObject(url, String.class, paramsMap); System.out.println(respStr); JSONObject respJson = restTpl.getForObject(url, JSONObject.class, paramsMap); System.out.println(respJson); } @Test public void testPost() throws Exception { String posturl = "http://xxx.xxx.xxx.xxx:8080/xxxx/xxxx/xxxxx"; JSONObject metadata = new JSONObject(); metadata.put("dddddd", "xxxxx"); metadata.put("ssssss", "xxxxxx"); metadata.put("flag", true); JSONObject paramsJson = new JSONObject(); paramsJson.put("mmmmm", "mmm"); paramsJson.put("nnnnn", "nnn"); paramsJson.put("password", "xxxxxxxxxxx"); paramsJson.put("metadata", metadata); String params = "RequestJson=" + URLEncoder.encode(paramsJson.toString(), "utf-8"); MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>(); headers.add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); HttpEntity<Object> hpEntity = new HttpEntity<Object>(params, headers); ResponseEntity<String> respEntity = restTpl.postForEntity(posturl, hpEntity, String.class); System.out.println(respEntity); } }
然而,就是這麼簡單的幾行代碼還不斷出錯~~~~~~~ java
RestTemplate中是如何處理請求頭信息的呢?web
以GET方法爲例,getForObject()方法中有這麼一句【RequestCallback requestCallback = acceptHeaderRequestCallback(responseType);】這裏爲何使用內部類呢?spring
複習下內部類的做用:json