• restTemplate get请求传body


    一、jari包

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.2</version>
    </dependency>

    二、定义HttpComponentsClientRestfulHttpRequestFactory

    import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
    import org.apache.http.client.methods.HttpUriRequest;
    import org.springframework.http.HttpMethod;
    import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
    
    import java.net.URI;
    
    public class HttpComponentsClientRestfulHttpRequestFactory extends HttpComponentsClientHttpRequestFactory {
    
        @Override
        protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
            if (httpMethod == HttpMethod.GET) {
                return new HttpGetRequestWithEntity(uri);
            }
            return super.createHttpUriRequest(httpMethod, uri);
        }
        //核心代码
        private static final class HttpGetRequestWithEntity extends HttpEntityEnclosingRequestBase {
            public HttpGetRequestWithEntity(final URI uri) {
                super.setURI(uri);
            }
    
            @Override
            public String getMethod() {
                return HttpMethod.GET.name();
            }
        }
    
    }

    三、使用

    RestTemplate restTemplate = new RestTemplate();
    //修改restTemplate的RequestFactory使其支持Get携带body参数
    restTemplate.setRequestFactory(new HttpComponentsClientRestfulHttpRequestFactory());
    
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    Map map= new HashMap();
    map.put("param", 123);
    HttpEntity<String> httpEntity = new HttpEntity<>(JSON.toJSONString(map), headers);
    
    ResponseEntity<String> exchange = restTemplate.exchange("your url", HttpMethod.GET, httpEntity, String.class);
  • 相关阅读:
    iOS开发——高级篇——iOS中常见的设计模式(MVC/单例/委托/观察者)
    object_getClassName swift得到类名
    UIGestureRecognizerDelegate设置响应事件优先级
    String to Double in swift
    Unable to boot device in current state:Booted
    xcode Indexing | Loading index...
    swift String to UTF8编码
    进入沙盒目录
    swift objective-c混编操作
    storyboard plain style unsupported in a navigation item
  • 原文地址:https://www.cnblogs.com/zeussbook/p/16486038.html
Copyright © 2020-2023  润新知